nameid
stringlengths 9
36
⌀ | content
stringlengths 2.12k
40.5k
⌀ | tokens
float64 511
10.1k
⌀ | LoC
float64 60
990
⌀ | Centain
int64 0
128
| Security issue
stringlengths 204
2.89k
⌀ | VulnNumber
int64 1
376
|
---|---|---|---|---|---|---|
35_ConcentratedLiquidityPosition.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0;
import "../../interfaces/IBentoBoxMinimal.sol";
import "../../interfaces/IConcentratedLiquidityPool.sol";
import "../../interfaces/IMasterDeployer.sol";
import "../../interfaces/ITridentRouter.sol";
import "../../libraries/concentratedPool/FullMath.sol";
import "./TridentNFT.sol";
import "hardhat/console.sol";
/// @notice Trident Concentrated Liquidity Pool periphery contract that combines non-fungible position management and staking.
abstract contract ConcentratedLiquidityPosition is TridentNFT {
event Mint(address indexed pool, address indexed recipient, uint256 indexed positionId);
event Burn(address indexed pool, address indexed owner, uint256 indexed positionId);
address public immutable wETH;
IBentoBoxMinimal public immutable bento;
IMasterDeployer public immutable masterDeployer;
mapping(uint256 => Position) public positions;
struct Position {
IConcentratedLiquidityPool pool;
uint128 liquidity;
int24 lower;
int24 upper;
uint256 feeGrowthInside0;
/// @dev Per unit of liquidity.
uint256 feeGrowthInside1;
}
constructor(address _wETH, address _masterDeployer) {
wETH = _wETH;
masterDeployer = IMasterDeployer(_masterDeployer);
bento = IBentoBoxMinimal(IMasterDeployer(_masterDeployer).bento());
}
function positionMintCallback(
address recipient,
int24 lower,
int24 upper,
uint128 amount,
uint256 feeGrowthInside0,
uint256 feeGrowthInside1
) external returns (uint256 positionId) {
require(IMasterDeployer(masterDeployer).pools(msg.sender), "NOT_POOL");
positions[totalSupply] = Position(IConcentratedLiquidityPool(msg.sender), amount, lower, upper, feeGrowthInside0, feeGrowthInside1);
positionId = totalSupply;
_mint(recipient);
emit Mint(msg.sender, recipient, positionId);
}
function burn(
uint256 tokenId,
uint128 amount,
address recipient,
bool unwrapBento
) external {
require(msg.sender == ownerOf[tokenId], "NOT_ID_OWNER");
Position storage position = positions[tokenId];
if (position.liquidity < amount) amount = position.liquidity;
position.pool.burn(abi.encode(position.lower, position.upper, amount, recipient, unwrapBento));
if (amount < position.liquidity) {
position.liquidity -= amount;
} else {
delete positions[tokenId];
_burn(tokenId);
}
emit Burn(address(position.pool), msg.sender, tokenId);
}
function collect(
uint256 tokenId,
address recipient,
bool unwrapBento
) external returns (uint256 token0amount, uint256 token1amount) {
require(msg.sender == ownerOf[tokenId], "NOT_ID_OWNER");
Position storage position = positions[tokenId];
(address token0, address token1) = _getAssets(position.pool);
{
(uint256 feeGrowthInside0, uint256 feeGrowthInside1) = position.pool.rangeFeeGrowth(position.lower, position.upper);
token0amount = FullMath.mulDiv(
feeGrowthInside0 - position.feeGrowthInside0,
position.liquidity,
0x100000000000000000000000000000000
);
token1amount = FullMath.mulDiv(
feeGrowthInside1 - position.feeGrowthInside1,
position.liquidity,
0x100000000000000000000000000000000
);
position.feeGrowthInside0 = feeGrowthInside0;
position.feeGrowthInside1 = feeGrowthInside1;
}
uint256 balance0 = bento.balanceOf(token0, address(this));
uint256 balance1 = bento.balanceOf(token1, address(this));
if (balance0 < token0amount || balance1 < token1amount) {
(uint256 amount0fees, uint256 amount1fees) = position.pool.collect(position.lower, position.upper, address(this), false);
uint256 newBalance0 = amount0fees + balance0;
uint256 newBalance1 = amount1fees + balance1;
/// @dev Rounding errors due to frequent claiming of other users in the same position may cost us some raw
if (token0amount > newBalance0) token0amount = newBalance0;
if (token1amount > newBalance1) token1amount = newBalance1;
}
_transfer(token0, address(this), recipient, token0amount, unwrapBento);
_transfer(token1, address(this), recipient, token1amount, unwrapBento);
}
function _getAssets(IConcentratedLiquidityPool pool) internal view returns (address token0, address token1) {
address[] memory pair = pool.getAssets();
token0 = pair[0];
token1 = pair[1];
}
function _transfer(
address token,
address from,
address to,
uint256 shares,
bool unwrapBento
) internal {
if (unwrapBento) {
bento.withdraw(token, from, to, 0, shares);
} else {
bento.transfer(token, from, to, shares);
}
}
} | 1,188 | 140 | 0 | 1. H-06: ConcentratedLiquidityPosition.sol#collect() Users may get double the amount of yield when they call collect() before burn() (Double Bonus)
When a user calls ConcentratedLiquidityPosition.sol#collect() to collect their yield, it calcuates the yield based on position.pool.rangeFeeGrowth() and position.feeGrowthInside0, position.feeGrowthInside1:
ConcentratedLiquidityPosition.sol#75 L101
When there are enough tokens in bento.balanceOf, it will not call position.pool.collect() to collect fees from the pool.
This makes the user who collect() their yield when there is enough balance to get double yield when they call burn() to remove liquidity. Because burn() will automatically collect fees on the pool contract.
2. H-07: ConcentratedLiquidityPosition.sol#burn() Wrong implementation allows attackers to steal yield (Lack of Access Control on Sensitive Functions)
When a user calls ConcentratedLiquidityPosition.sol#burn() to burn their liquidity, it calls ConcentratedLiquidityPool.sol#burn() -> _updatePosition():
ConcentratedLiquidityPosition.sol#525 L553
The _updatePosition() function will return amount0fees and amount1fees of the whole position with the lower and upper tick and send them to the recipient alongside the burned liquidity amounts.
3. [M-06] ConcentratedLiquidityPosition.collect(), balances of `token0` and `token1` in bento will be used to pay the fees. (Price oracle dependence)
In the case of someone add an incentive with token0 or token1, the incentive in the balance of bento will be used to pay fees until the balance is completely consumed. As a result, when a user calls claimReward(), the contract may not have enough balance to pay (it supposed to have it), cause the transaction to fail.
| 3 |
44_Swap.sol | pragma solidity ^0.8.0;
import "../governance/EmergencyPausable.sol";
import "../utils/Math.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract Swap is EmergencyPausable, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Math for uint256;
/// @notice An address to receive swap fees. The 0 address prevents fee
/// withdrawal.
address payable public feeRecipient;
/// @notice divide by the SWAP_FEE_DIVISOR to get the fee ratio, deducted
/// from the proceeds of each swap.
uint256 public swapFee;
uint256 public constant SWAP_FEE_DIVISOR = 100_000;
event SwappedTokens(
address tokenSold,
address tokenBought,
uint256 amountSold,
uint256 amountBought,
uint256 amountBoughtFee
);
event NewSwapFee(
uint256 newSwapFee
);
event NewFeeRecipient(
address newFeeRecipient
);
event FeesSwept(
address token,
uint256 amount,
address recipient
);
/// @param owner_ A new contract owner, expected to implement
/// TimelockGovernorWithEmergencyGovernance.
/// @param feeRecipient_ A payable address to receive swap fees. Setting the
/// 0 address prevents fee withdrawal, and can be set later by
/// governance.
/// @param swapFee_ A fee, which divided by SWAP_FEE_DIVISOR sets the fee
/// ratio charged for each swap.
constructor(address owner_, address payable feeRecipient_, uint256 swapFee_) {
require(owner_ != address(0), "Swap::constructor: Owner must not be 0");
transferOwnership(owner_);
feeRecipient = feeRecipient_;
emit NewFeeRecipient(feeRecipient);
swapFee = swapFee_;
emit NewSwapFee(swapFee);
}
/// @notice Set the fee taken from each swap's proceeds.
/// @dev Only timelocked governance can set the swap fee.
/// @param swapFee_ A fee, which divided by SWAP_FEE_DIVISOR sets the fee ratio.
function setSwapFee(uint256 swapFee_) external onlyTimelock {
require(swapFee_ < SWAP_FEE_DIVISOR, "Swap::setSwapFee: Swap fee must not exceed 100%");
swapFee = swapFee_;
emit NewSwapFee(swapFee);
}
/// @notice Set the address permitted to receive swap fees.
/// @dev Only timelocked governance can set the fee recipient.
/// @param feeRecipient_ A payable address to receive swap fees. Setting the
/// 0 address prevents fee withdrawal.
function setFeeRecipient(address payable feeRecipient_) external onlyTimelock {
feeRecipient = feeRecipient_;
emit NewFeeRecipient(feeRecipient);
}
/// @notice Swap by filling a 0x quote.
/// @dev Execute a swap by filling a 0x quote, as provided by the 0x API.
/// Charges a governable swap fee that comes out of the bought asset,
/// be it token or ETH. Unfortunately, the fee is also charged on any
/// refunded ETH from 0x protocol fees due to an implementation oddity.
/// This behavior shouldn't impact most users.
///
/// Learn more about the 0x API and quotes at https://0x.org/docs/api
/// @param zrxSellTokenAddress The contract address of the token to be sold,
/// as returned by the 0x `/swap/v1/quote` API endpoint. If selling
/// unwrapped ETH included via msg.value, this should be address(0)
/// @param amountToSell Amount of token to sell, with the same precision as
/// zrxSellTokenAddress. This information is also encoded in zrxData.
/// If selling unwrapped ETH via msg.value, this should be 0.
/// @param zrxBuyTokenAddress The contract address of the token to be bought,
/// as returned by the 0x `/swap/v1/quote` API endpoint. To buy
/// unwrapped ETH, use `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`
/// @param minimumAmountReceived The minimum amount expected to be received
/// from filling the quote, before the swap fee is deducted, in
/// zrxBuyTokenAddress. Reverts if not met
/// @param zrxAllowanceTarget Contract address that needs to be approved for
/// zrxSellTokenAddress, as returned by the 0x `/swap/v1/quote` API
/// endpoint. Should be address(0) for purchases uses unwrapped ETH
/// @param zrxTo Contract to fill the 0x quote, as returned by the 0x
/// `/swap/v1/quote` API endpoint
/// @param zrxData Data encoding the 0x quote, as returned by the 0x
/// `/swap/v1/quote` API endpoint
/// @param deadline Timestamp after which the swap will be reverted.
function swapByQuote(
address zrxSellTokenAddress,
uint256 amountToSell,
address zrxBuyTokenAddress,
uint256 minimumAmountReceived,
address zrxAllowanceTarget,
address payable zrxTo,
bytes calldata zrxData,
uint256 deadline
) external payable whenNotPaused nonReentrant {
require(
block.timestamp <= deadline,
"Swap::swapByQuote: Deadline exceeded"
);
require(
!signifiesETHOrZero(zrxSellTokenAddress) || msg.value > 0,
"Swap::swapByQuote: Unwrapped ETH must be swapped via msg.value"
);
// if zrxAllowanceTarget is 0, this is an ETH sale
if (zrxAllowanceTarget != address(0)) {
// transfer tokens to this contract
IERC20(zrxSellTokenAddress).safeTransferFrom(msg.sender, address(this), amountToSell);
// approve token transfer to 0x contracts
// TODO (handle approval special cases like USDT, KNC, etc)
IERC20(zrxSellTokenAddress).safeIncreaseAllowance(zrxAllowanceTarget, amountToSell);
}
// execute 0x quote
(uint256 boughtERC20Amount, uint256 boughtETHAmount) = fillZrxQuote(
IERC20(zrxBuyTokenAddress),
zrxTo,
zrxData,
msg.value
);
require(
(
!signifiesETHOrZero(zrxBuyTokenAddress) &&
boughtERC20Amount >= minimumAmountReceived
) ||
(
signifiesETHOrZero(zrxBuyTokenAddress) &&
boughtETHAmount >= minimumAmountReceived
),
"Swap::swapByQuote: Minimum swap proceeds requirement not met"
);
if (boughtERC20Amount > 0) {
// take the swap fee from the ERC20 proceeds and return the rest
uint256 toTransfer = SWAP_FEE_DIVISOR.sub(swapFee).mul(boughtERC20Amount).div(SWAP_FEE_DIVISOR);
IERC20(zrxBuyTokenAddress).safeTransfer(msg.sender, toTransfer);
// return any refunded ETH
payable(msg.sender).transfer(boughtETHAmount);
emit SwappedTokens(
zrxSellTokenAddress,
zrxBuyTokenAddress,
amountToSell,
boughtERC20Amount,
boughtERC20Amount.sub(toTransfer)
);
} else {
// take the swap fee from the ETH proceeds and return the rest. Note
// that if any 0x protocol fee is refunded in ETH, it also suffers
// the swap fee tax
uint256 toTransfer = SWAP_FEE_DIVISOR.sub(swapFee).mul(boughtETHAmount).div(SWAP_FEE_DIVISOR);
payable(msg.sender).transfer(toTransfer);
emit SwappedTokens(
zrxSellTokenAddress,
zrxBuyTokenAddress,
amountToSell,
boughtETHAmount,
boughtETHAmount.sub(toTransfer)
);
}
if (zrxAllowanceTarget != address(0)) {
// remove any dangling token allowance
IERC20(zrxSellTokenAddress).safeApprove(zrxAllowanceTarget, 0);
}
}
/// @notice Fill a 0x quote as provided by the API, and return any ETH or
/// ERC20 proceeds.
/// @dev Learn more at https://0x.org/docs/api
/// @param zrxBuyTokenAddress The contract address of the token to be bought,
/// as provided by the 0x API. `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee`
/// signifies the user is buying unwrapped ETH.
/// @param zrxTo Contract to fill the 0x quote, as provided by the 0x API
/// @param zrxData Data encoding the 0x quote, as provided by the 0x API
/// @param ethAmount The amount of ETH required to fill the quote, including
/// any ETH being traded as well as protocol fees
/// @return any positive `zrxBuyTokenAddress` ERC20 balance change, as well
/// as any positive ETH balance change
function fillZrxQuote(
IERC20 zrxBuyTokenAddress,
address payable zrxTo,
bytes calldata zrxData,
uint256 ethAmount
) internal returns (uint256, uint256) {
uint256 originalERC20Balance = 0;
if(!signifiesETHOrZero(address(zrxBuyTokenAddress))) {
originalERC20Balance = zrxBuyTokenAddress.balanceOf(address(this));
}
uint256 originalETHBalance = address(this).balance;
(bool success,) = zrxTo.call{value: ethAmount}(zrxData);
require(success, "Swap::fillZrxQuote: Failed to fill quote");
uint256 ethDelta = address(this).balance.subOrZero(originalETHBalance);
uint256 erc20Delta;
if(!signifiesETHOrZero(address(zrxBuyTokenAddress))) {
erc20Delta = zrxBuyTokenAddress.balanceOf(address(this)).subOrZero(originalERC20Balance);
require(erc20Delta > 0, "Swap::fillZrxQuote: Didn't receive bought token");
} else {
require(ethDelta > 0, "Swap::fillZrxQuote: Didn't receive bought ETH");
}
return (erc20Delta, ethDelta);
}
/// @notice Test whether an address is zero, or the magic address the 0x
/// platform uses to signify "unwrapped ETH" rather than an ERC20.
/// @param tokenAddress An address that might point toward an ERC-20.
function signifiesETHOrZero(address tokenAddress) internal pure returns (bool) {
return (
tokenAddress == address(0) ||
tokenAddress == address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee)
);
}
/// @notice Sweeps accrued ETH and ERC20 swap fees to the pre-established
/// fee recipient address.
/// @dev Fees are tracked based on the contract's balances, rather than
/// using any additional bookkeeping. If there are bugs in swap
/// accounting, this function could jeopardize funds.
/// @param tokens An array of ERC20 contracts to withdraw token fees
function sweepFees(
address[] calldata tokens
) external nonReentrant {
require(
feeRecipient != address(0),
"Swap::withdrawAccruedFees: feeRecipient is not initialized"
);
for (uint8 i = 0; i<tokens.length; i++) {
uint256 balance = IERC20(tokens[i]).balanceOf(address(this));
if (balance > 0) {
IERC20(tokens[i]).safeTransfer(feeRecipient, balance);
emit FeesSwept(tokens[i], balance, feeRecipient);
}
}
feeRecipient.transfer(address(this).balance);
emit FeesSwept(address(0), address(this).balance, feeRecipient);
}
fallback() external payable {}
receive() external payable {}
} | 2,733 | 264 | 1 | 1. H-01 Arbitrary contract call allows attackers to steal ERC20 from users' wallets (Unchecked external calls)
Swap.sol L220-L212 A call to an arbitrary contract with custom calldata is made in fillZrxQuote(), which means the contract can be an ERC20 token, and the calldata can be `transferFrom` a previously approved user.
2. H-02 Wrong calculation of erc20Delta and ethDelta (Use of `msg.value`)
Swap.sol L200-L225 When a user tries to swap unwrapped ETH to ERC20, even if there is a certain amount of ETH refunded, at L215 in fillZrxQuote(), ethDelta will always be 0. That's because originalETHBalance already includes the msg.value sent by the caller.
3. M-01: Swap.sol implements potentially dangerous transfer (Use of `transfer()`, Unchecked Transfer)
The use of transfer() in Swap.sol may have unintended outcomes on the eth being sent to the receiver. Eth may be irretrievable or undelivered if the msg.sender or feeRecipient is a smart contract.
4. M-02 Unused ERC20 tokens are not refunded
Based on the context and comments in the code, we assume that it's possible that there will be some leftover sell tokens, not only when users are selling unwrapped ETH but also for ERC20 tokens. However, in the current implementation, only refunded ETH is returned (L158). Because of this, the leftover tkoens may be left in the contract unintentionally.
5. [M-03] Users can avoid paying fees for ETH swaps
Users can call Swap.swapByQuote() to execute an ETH swap (where they receive ETH) without paying swap fee for the gained ETH. They can trick the system by setting zrxBuyTokenAddress to an address of a malicious contract and making it think they have executed an ERC20 swap when they have actually executed an ETH swap. In this case, the system will give them the ETH they got from the swap (boughtETHAmount) without charging any swap fees for it, because the systems consideres this ETH as "refunded ETH" that wasn't part of the "ERC20" swap. | 5 |
3_MarginRouter.sol | // SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "../libraries/UniswapStyleLib.sol";
import "./RoleAware.sol";
import "./Fund.sol";
import "../interfaces/IMarginTrading.sol";
import "./Lending.sol";
import "./Admin.sol";
import "./IncentivizedHolder.sol";
/// @title Top level transaction controller
contract MarginRouter is RoleAware, IncentivizedHolder, Ownable {
/// @notice wrapped ETH ERC20 contract
address public immutable WETH;
uint256 public constant mswapFeesPer10k = 10;
/// emitted when a trader depoits on cross margin
event CrossDeposit(
address trader,
address depositToken,
uint256 depositAmount
);
/// emitted whenever a trade happens
event CrossTrade(
address trader,
address inToken,
uint256 inTokenAmount,
uint256 inTokenBorrow,
address outToken,
uint256 outTokenAmount,
uint256 outTokenExtinguish
);
/// emitted when a trader withdraws funds
event CrossWithdraw(
address trader,
address withdrawToken,
uint256 withdrawAmount
);
/// emitted upon sucessfully borrowing
event CrossBorrow(
address trader,
address borrowToken,
uint256 borrowAmount
);
/// emmited on deposit-borrow-withdraw
event CrossOvercollateralizedBorrow(
address trader,
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
);
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "Trade has expired");
_;
}
constructor(address _WETH, address _roles) RoleAware(_roles) {
WETH = _WETH;
}
/// @notice traders call this to deposit funds on cross margin
function crossDeposit(address depositToken, uint256 depositAmount)
external
{
Fund(fund()).depositFor(msg.sender, depositToken, depositAmount);
uint256 extinguishAmount =
IMarginTrading(marginTrading()).registerDeposit(
msg.sender,
depositToken,
depositAmount
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(depositToken, extinguishAmount);
withdrawClaim(msg.sender, depositToken, extinguishAmount);
}
emit CrossDeposit(msg.sender, depositToken, depositAmount);
}
/// @notice deposit wrapped ehtereum into cross margin account
function crossDepositETH() external payable {
Fund(fund()).depositToWETH{value: msg.value}();
uint256 extinguishAmount =
IMarginTrading(marginTrading()).registerDeposit(
msg.sender,
WETH,
msg.value
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(WETH, extinguishAmount);
withdrawClaim(msg.sender, WETH, extinguishAmount);
}
emit CrossDeposit(msg.sender, WETH, msg.value);
}
/// @notice withdraw deposits/earnings from cross margin account
function crossWithdraw(address withdrawToken, uint256 withdrawAmount)
external
{
IMarginTrading(marginTrading()).registerWithdrawal(
msg.sender,
withdrawToken,
withdrawAmount
);
Fund(fund()).withdraw(withdrawToken, msg.sender, withdrawAmount);
emit CrossWithdraw(msg.sender, withdrawToken, withdrawAmount);
}
/// @notice withdraw ethereum from cross margin account
function crossWithdrawETH(uint256 withdrawAmount) external {
IMarginTrading(marginTrading()).registerWithdrawal(
msg.sender,
WETH,
withdrawAmount
);
Fund(fund()).withdrawETH(msg.sender, withdrawAmount);
}
/// @notice borrow into cross margin trading account
function crossBorrow(address borrowToken, uint256 borrowAmount) external {
Lending(lending()).registerBorrow(borrowToken, borrowAmount);
IMarginTrading(marginTrading()).registerBorrow(
msg.sender,
borrowToken,
borrowAmount
);
stakeClaim(msg.sender, borrowToken, borrowAmount);
emit CrossBorrow(msg.sender, borrowToken, borrowAmount);
}
/// @notice convenience function to perform overcollateralized borrowing
/// against a cross margin account.
/// @dev caution: the account still has to have a positive balaance at the end
/// of the withdraw. So an underwater account may not be able to withdraw
function crossOvercollateralizedBorrow(
address depositToken,
uint256 depositAmount,
address borrowToken,
uint256 withdrawAmount
) external {
Fund(fund()).depositFor(msg.sender, depositToken, depositAmount);
Lending(lending()).registerBorrow(borrowToken, withdrawAmount);
IMarginTrading(marginTrading()).registerOvercollateralizedBorrow(
msg.sender,
depositToken,
depositAmount,
borrowToken,
withdrawAmount
);
Fund(fund()).withdraw(borrowToken, msg.sender, withdrawAmount);
stakeClaim(msg.sender, borrowToken, withdrawAmount);
emit CrossOvercollateralizedBorrow(
msg.sender,
depositToken,
depositAmount,
borrowToken,
withdrawAmount
);
}
/// @notice close an account that is no longer borrowing and return gains
function crossCloseAccount() external {
(address[] memory holdingTokens, uint256[] memory holdingAmounts) =
IMarginTrading(marginTrading()).getHoldingAmounts(msg.sender);
// requires all debts paid off
IMarginTrading(marginTrading()).registerLiquidation(msg.sender);
for (uint256 i; holdingTokens.length > i; i++) {
Fund(fund()).withdraw(
holdingTokens[i],
msg.sender,
holdingAmounts[i]
);
}
}
// **** SWAP ****
/// @dev requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory pairs,
address[] memory tokens,
address _to
) internal virtual {
address outToken = tokens[tokens.length - 1];
uint256 startingBalance = IERC20(outToken).balanceOf(_to);
for (uint256 i; i < pairs.length; i++) {
(address input, address output) = (tokens[i], tokens[i + 1]);
(address token0, ) = UniswapStyleLib.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < pairs.length - 1 ? pairs[i + 1] : _to;
IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]);
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
uint256 endingBalance = IERC20(outToken).balanceOf(_to);
require(
endingBalance >= startingBalance + amounts[amounts.length - 1],
"Defective AMM route; balances don't match"
);
}
/// @dev internal helper swapping exact token for token on AMM
function _swapExactT4T(
uint256[] memory amounts,
uint256 amountOutMin,
address[] calldata pairs,
address[] calldata tokens
) internal {
require(
amounts[amounts.length - 1] >= amountOutMin,
"MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]);
_swap(amounts, pairs, tokens, fund());
}
/// @notice make swaps on AMM using protocol funds, only for authorized contracts
function authorizedSwapExactT4T(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata pairs,
address[] calldata tokens
) external returns (uint256[] memory amounts) {
require(
isAuthorizedFundTrader(msg.sender),
"Calling contract is not authorized to trade with protocl funds"
);
amounts = UniswapStyleLib.getAmountsOut(amountIn, pairs, tokens);
_swapExactT4T(amounts, amountOutMin, pairs, tokens);
}
// @dev internal helper swapping exact token for token on on AMM
function _swapT4ExactT(
uint256[] memory amounts,
uint256 amountInMax,
address[] calldata pairs,
address[] calldata tokens
) internal {
// TODO minimum trade?
require(
amounts[0] <= amountInMax,
"MarginRouter: EXCESSIVE_INPUT_AMOUNT"
);
Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]);
_swap(amounts, pairs, tokens, fund());
}
//// @notice swap protocol funds on AMM, only for authorized
function authorizedSwapT4ExactT(
uint256 amountOut,
uint256 amountInMax,
address[] calldata pairs,
address[] calldata tokens
) external returns (uint256[] memory amounts) {
require(
isAuthorizedFundTrader(msg.sender),
"Calling contract is not authorized to trade with protocl funds"
);
amounts = UniswapStyleLib.getAmountsIn(amountOut, pairs, tokens);
_swapT4ExactT(amounts, amountInMax, pairs, tokens);
}
/// @notice entry point for swapping tokens held in cross margin account
function crossSwapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata pairs,
address[] calldata tokens,
uint256 deadline
) external ensure(deadline) returns (uint256[] memory amounts) {
// calc fees
uint256 fees = takeFeesFromInput(amountIn);
// swap
amounts = UniswapStyleLib.getAmountsOut(amountIn - fees, pairs, tokens);
// checks that trader is within allowed lending bounds
registerTrade(
msg.sender,
tokens[0],
tokens[tokens.length - 1],
amountIn,
amounts[amounts.length - 1]
);
_swapExactT4T(amounts, amountOutMin, pairs, tokens);
}
/// @notice entry point for swapping tokens held in cross margin account
function crossSwapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata pairs,
address[] calldata tokens,
uint256 deadline
) external ensure(deadline) returns (uint256[] memory amounts) {
// swap
amounts = UniswapStyleLib.getAmountsIn(
amountOut + takeFeesFromOutput(amountOut),
pairs,
tokens
);
// checks that trader is within allowed lending bounds
registerTrade(
msg.sender,
tokens[0],
tokens[tokens.length - 1],
amounts[0],
amountOut
);
_swapT4ExactT(amounts, amountInMax, pairs, tokens);
}
/// @dev helper function does all the work of telling other contracts
/// about a trade
function registerTrade(
address trader,
address inToken,
address outToken,
uint256 inAmount,
uint256 outAmount
) internal {
(uint256 extinguishAmount, uint256 borrowAmount) =
IMarginTrading(marginTrading()).registerTradeAndBorrow(
trader,
inToken,
outToken,
inAmount,
outAmount
);
if (extinguishAmount > 0) {
Lending(lending()).payOff(outToken, extinguishAmount);
withdrawClaim(trader, outToken, extinguishAmount);
}
if (borrowAmount > 0) {
Lending(lending()).registerBorrow(inToken, borrowAmount);
stakeClaim(trader, inToken, borrowAmount);
}
emit CrossTrade(
trader,
inToken,
inAmount,
borrowAmount,
outToken,
outAmount,
extinguishAmount
);
}
function getAmountsOut(
uint256 inAmount,
address[] calldata pairs,
address[] calldata tokens
) external view returns (uint256[] memory) {
return UniswapStyleLib.getAmountsOut(inAmount, pairs, tokens);
}
function getAmountsIn(
uint256 outAmount,
address[] calldata pairs,
address[] calldata tokens
) external view returns (uint256[] memory) {
return UniswapStyleLib.getAmountsIn(outAmount, pairs, tokens);
}
function takeFeesFromOutput(uint256 amount)
internal
pure
returns (uint256 fees)
{
fees = (mswapFeesPer10k * amount) / 10_000;
}
function takeFeesFromInput(uint256 amount)
internal
pure
returns (uint256 fees)
{
fees = (mswapFeesPer10k * amount) / (10_000 + mswapFeesPer10k);
}
} | 2,888 | 403 | 1 | 1. [H-01]: Re-entrancy bug allows inflating balance (Reentrancy, Lack of Input Validation)
One can call the MarginRouter.crossSwapExactTokensForTokens function first with a fake contract disguised as a token pair: crossSwapExactTokensForTokens(0.0001 WETH, 0, [ATTACKER_CONTRACT], [WETH, WBTC]). When the amounts are computed by the amounts = UniswapStyleLib.getAmountsOut(amountIn - fees, pairs, tokens); call, the attacker contract returns fake reserves that yield 1 WBTC for the tiny input.
2. [H-02]: Missing fromToken != toToken check
Attacker calls MarginRouter.crossSwapExactTokensForTokens with a fake pair and the same token[0] == token[1]. crossSwapExactTokensForTokens(1000 WETH, 0, [ATTACKER_CONTRACT], [WETH, WETH])
3. [H-07] account.holdsToken is never set
The MarginRouter.crossCloseAccount function uses these wrong amounts to withdraw all tokens:
4. [M-03]: No entry checks in crossSwap[Exact]TokensFor[Exact]Tokens (Unchecked external calls)
The functions crossSwapTokensForExactTokens and crossSwapExactTokensForTokens of MarginRouter.sol do not check who is calling the function. They also do not check the contents of pairs and tokens nor do they check if the size of pairs and tokens is the same. | 3 |
70_LiquidityBasedTWAP.sol | // SPDX-License-Identifier: Unlicense
pragma solidity =0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../external/libraries/UniswapV2OracleLibrary.sol";
import "../interfaces/external/chainlink/IAggregatorV3.sol";
import "../interfaces/external/uniswap/IUniswapV2Pair.sol";
import "../interfaces/lbt/ILiquidityBasedTWAP.sol";
import "../interfaces/dex-v2/pool/IVaderPoolV2.sol";
contract LiquidityBasedTWAP is ILiquidityBasedTWAP, Ownable {
/* ========== LIBRARIES ========== */
using FixedPoint for FixedPoint.uq112x112;
using FixedPoint for FixedPoint.uq144x112;
/* ========== STATE VARIABLES ========== */
address public immutable vader;
IVaderPoolV2 public immutable vaderPool;
IUniswapV2Pair[] public vaderPairs;
IERC20[] public usdvPairs;
uint256 public override maxUpdateWindow;
uint256[2] public totalLiquidityWeight;
uint256[2] public override previousPrices;
mapping(address => ExchangePair) public twapData;
mapping(address => IAggregatorV3) public oracles;
/* ========== CONSTRUCTOR ========== */
constructor(address _vader, IVaderPoolV2 _vaderPool) {
require(
_vader != address(0) && _vaderPool != IVaderPoolV2(address(0)),
"LBTWAP::construction: Zero Address"
);
vader = _vader;
vaderPool = _vaderPool;
}
/* ========== VIEWS ========== */
function getStaleVaderPrice() external view returns (uint256) {
uint256 totalPairs = vaderPairs.length;
uint256[] memory pastLiquidityWeights = new uint256[](totalPairs);
uint256 pastTotalLiquidityWeight = totalLiquidityWeight[
uint256(Paths.VADER)
];
for (uint256 i; i < totalPairs; ++i)
pastLiquidityWeights[i] = twapData[address(vaderPairs[i])]
.pastLiquidityEvaluation;
return
_calculateVaderPrice(
pastLiquidityWeights,
pastTotalLiquidityWeight
);
}
function getStaleUSDVPrice() external view returns (uint256) {
uint256 totalPairs = usdvPairs.length;
uint256[] memory pastLiquidityWeights = new uint256[](totalPairs);
uint256 pastTotalLiquidityWeight = totalLiquidityWeight[
uint256(Paths.USDV)
];
for (uint256 i; i < totalPairs; ++i)
pastLiquidityWeights[i] = twapData[address(usdvPairs[i])]
.pastLiquidityEvaluation;
return
_calculateUSDVPrice(pastLiquidityWeights, pastTotalLiquidityWeight);
}
function getChainlinkPrice(address asset) public view returns (uint256) {
IAggregatorV3 oracle = oracles[asset];
(uint80 roundID, int256 price, , , uint80 answeredInRound) = oracle
.latestRoundData();
require(
answeredInRound >= roundID,
"LBTWAP::getChainlinkPrice: Stale Chainlink Price"
);
require(price > 0, "LBTWAP::getChainlinkPrice: Chainlink Malfunction");
return uint256(price);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function getVaderPrice() external returns (uint256) {
(
uint256[] memory pastLiquidityWeights,
uint256 pastTotalLiquidityWeight
) = syncVaderPrice();
return
_calculateVaderPrice(
pastLiquidityWeights,
pastTotalLiquidityWeight
);
}
function syncVaderPrice()
public
override
returns (
uint256[] memory pastLiquidityWeights,
uint256 pastTotalLiquidityWeight
)
{
uint256 _totalLiquidityWeight;
uint256 totalPairs = vaderPairs.length;
pastLiquidityWeights = new uint256[](totalPairs);
pastTotalLiquidityWeight = totalLiquidityWeight[uint256(Paths.VADER)];
for (uint256 i; i < totalPairs; ++i) {
IUniswapV2Pair pair = vaderPairs[i];
ExchangePair storage pairData = twapData[address(pair)];
uint256 timeElapsed = block.timestamp - pairData.lastMeasurement;
if (timeElapsed < pairData.updatePeriod) continue;
uint256 pastLiquidityEvaluation = pairData.pastLiquidityEvaluation;
uint256 currentLiquidityEvaluation = _updateVaderPrice(
pair,
pairData,
timeElapsed
);
pastLiquidityWeights[i] = pastLiquidityEvaluation;
pairData.pastLiquidityEvaluation = currentLiquidityEvaluation;
_totalLiquidityWeight += currentLiquidityEvaluation;
}
totalLiquidityWeight[uint256(Paths.VADER)] = _totalLiquidityWeight;
}
function _updateVaderPrice(
IUniswapV2Pair pair,
ExchangePair storage pairData,
uint256 timeElapsed
) internal returns (uint256 currentLiquidityEvaluation) {
bool isFirst = pair.token0() == vader;
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveNative, uint256 reserveForeign) = isFirst
? (reserve0, reserve1)
: (reserve1, reserve0);
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint256 currentMeasurement
) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint256 nativeTokenPriceCumulative = isFirst
? price0Cumulative
: price1Cumulative;
unchecked {
pairData.nativeTokenPriceAverage = FixedPoint.uq112x112(
uint224(
(nativeTokenPriceCumulative -
pairData.nativeTokenPriceCumulative) / timeElapsed
)
);
}
pairData.nativeTokenPriceCumulative = nativeTokenPriceCumulative;
pairData.lastMeasurement = currentMeasurement;
currentLiquidityEvaluation =
(reserveNative * previousPrices[uint256(Paths.VADER)]) +
(reserveForeign * getChainlinkPrice(pairData.foreignAsset));
}
function _calculateVaderPrice(
uint256[] memory liquidityWeights,
uint256 totalVaderLiquidityWeight
) internal view returns (uint256) {
uint256 totalUSD;
uint256 totalVader;
uint256 totalPairs = vaderPairs.length;
for (uint256 i; i < totalPairs; ++i) {
IUniswapV2Pair pair = vaderPairs[i];
ExchangePair storage pairData = twapData[address(pair)];
uint256 foreignPrice = getChainlinkPrice(pairData.foreignAsset);
totalUSD +=
(foreignPrice * liquidityWeights[i]) /
totalVaderLiquidityWeight;
totalVader +=
(pairData
.nativeTokenPriceAverage
.mul(pairData.foreignUnit)
.decode144() * liquidityWeights[i]) /
totalVaderLiquidityWeight;
}
// NOTE: Accuracy of VADER & USDV is 18 decimals == 1 ether
return (totalUSD * 1 ether) / totalVader;
}
function setupVader(
IUniswapV2Pair pair,
IAggregatorV3 oracle,
uint256 updatePeriod,
uint256 vaderPrice
) external onlyOwner {
require(
previousPrices[uint256(Paths.VADER)] == 0,
"LBTWAP::setupVader: Already Initialized"
);
previousPrices[uint256(Paths.VADER)] = vaderPrice;
_addVaderPair(pair, oracle, updatePeriod);
}
// NOTE: Discuss whether minimum paired liquidity value should be enforced at code level
function addVaderPair(
IUniswapV2Pair pair,
IAggregatorV3 oracle,
uint256 updatePeriod
) external onlyOwner {
require(
previousPrices[uint256(Paths.VADER)] != 0,
"LBTWAP::addVaderPair: Vader Uninitialized"
);
_addVaderPair(pair, oracle, updatePeriod);
}
function _addVaderPair(
IUniswapV2Pair pair,
IAggregatorV3 oracle,
uint256 updatePeriod
) internal {
require(
updatePeriod != 0,
"LBTWAP::addVaderPair: Incorrect Update Period"
);
require(oracle.decimals() == 8, "LBTWAP::addVaderPair: Non-USD Oracle");
ExchangePair storage pairData = twapData[address(pair)];
bool isFirst = pair.token0() == vader;
(address nativeAsset, address foreignAsset) = isFirst
? (pair.token0(), pair.token1())
: (pair.token1(), pair.token0());
oracles[foreignAsset] = oracle;
require(nativeAsset == vader, "LBTWAP::addVaderPair: Unsupported Pair");
pairData.foreignAsset = foreignAsset;
pairData.foreignUnit = uint96(
10**uint256(IERC20Metadata(foreignAsset).decimals())
);
pairData.updatePeriod = updatePeriod;
pairData.lastMeasurement = block.timestamp;
pairData.nativeTokenPriceCumulative = isFirst
? pair.price0CumulativeLast()
: pair.price1CumulativeLast();
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveNative, uint256 reserveForeign) = isFirst
? (reserve0, reserve1)
: (reserve1, reserve0);
uint256 pairLiquidityEvaluation = (reserveNative *
previousPrices[uint256(Paths.VADER)]) +
(reserveForeign * getChainlinkPrice(foreignAsset));
pairData.pastLiquidityEvaluation = pairLiquidityEvaluation;
totalLiquidityWeight[uint256(Paths.VADER)] += pairLiquidityEvaluation;
vaderPairs.push(pair);
if (maxUpdateWindow < updatePeriod) maxUpdateWindow = updatePeriod;
}
function getUSDVPrice() external returns (uint256) {
(
uint256[] memory pastLiquidityWeights,
uint256 pastTotalLiquidityWeight
) = syncUSDVPrice();
return
_calculateUSDVPrice(pastLiquidityWeights, pastTotalLiquidityWeight);
}
function syncUSDVPrice()
public
override
returns (
uint256[] memory pastLiquidityWeights,
uint256 pastTotalLiquidityWeight
)
{
uint256 _totalLiquidityWeight;
uint256 totalPairs = usdvPairs.length;
pastLiquidityWeights = new uint256[](totalPairs);
pastTotalLiquidityWeight = totalLiquidityWeight[uint256(Paths.USDV)];
for (uint256 i; i < totalPairs; ++i) {
IERC20 foreignAsset = usdvPairs[i];
ExchangePair storage pairData = twapData[address(foreignAsset)];
uint256 timeElapsed = block.timestamp - pairData.lastMeasurement;
if (timeElapsed < pairData.updatePeriod) continue;
uint256 pastLiquidityEvaluation = pairData.pastLiquidityEvaluation;
uint256 currentLiquidityEvaluation = _updateUSDVPrice(
foreignAsset,
pairData,
timeElapsed
);
pastLiquidityWeights[i] = pastLiquidityEvaluation;
pairData.pastLiquidityEvaluation = currentLiquidityEvaluation;
_totalLiquidityWeight += currentLiquidityEvaluation;
}
totalLiquidityWeight[uint256(Paths.USDV)] = _totalLiquidityWeight;
}
function _updateUSDVPrice(
IERC20 foreignAsset,
ExchangePair storage pairData,
uint256 timeElapsed
) internal returns (uint256 currentLiquidityEvaluation) {
(uint256 reserveNative, uint256 reserveForeign, ) = vaderPool
.getReserves(foreignAsset);
(
uint256 nativeTokenPriceCumulative,
,
uint256 currentMeasurement
) = vaderPool.cumulativePrices(foreignAsset);
unchecked {
pairData.nativeTokenPriceAverage = FixedPoint.uq112x112(
uint224(
(nativeTokenPriceCumulative -
pairData.nativeTokenPriceCumulative) / timeElapsed
)
);
}
pairData.nativeTokenPriceCumulative = nativeTokenPriceCumulative;
pairData.lastMeasurement = currentMeasurement;
currentLiquidityEvaluation =
(reserveNative * previousPrices[uint256(Paths.USDV)]) +
(reserveForeign * getChainlinkPrice(address(foreignAsset)));
}
function _calculateUSDVPrice(
uint256[] memory liquidityWeights,
uint256 totalUSDVLiquidityWeight
) internal view returns (uint256) {
uint256 totalUSD;
uint256 totalUSDV;
uint256 totalPairs = usdvPairs.length;
for (uint256 i; i < totalPairs; ++i) {
IERC20 foreignAsset = usdvPairs[i];
ExchangePair storage pairData = twapData[address(foreignAsset)];
uint256 foreignPrice = getChainlinkPrice(address(foreignAsset));
totalUSD +=
(foreignPrice * liquidityWeights[i]) /
totalUSDVLiquidityWeight;
totalUSDV +=
(pairData
.nativeTokenPriceAverage
.mul(pairData.foreignUnit)
.decode144() * liquidityWeights[i]) /
totalUSDVLiquidityWeight;
}
// NOTE: Accuracy of VADER & USDV is 18 decimals == 1 ether
return (totalUSD * 1 ether) / totalUSDV;
}
function setupUSDV(
IERC20 foreignAsset,
IAggregatorV3 oracle,
uint256 updatePeriod,
uint256 usdvPrice
) external onlyOwner {
require(
previousPrices[uint256(Paths.USDV)] == 0,
"LBTWAP::setupUSDV: Already Initialized"
);
previousPrices[uint256(Paths.USDV)] = usdvPrice;
_addUSDVPair(foreignAsset, oracle, updatePeriod);
}
// NOTE: Discuss whether minimum paired liquidity value should be enforced at code level
function addUSDVPair(
IERC20 foreignAsset,
IAggregatorV3 oracle,
uint256 updatePeriod
) external onlyOwner {
require(
previousPrices[uint256(Paths.USDV)] != 0,
"LBTWAP::addUSDVPair: USDV Uninitialized"
);
_addUSDVPair(foreignAsset, oracle, updatePeriod);
}
function _addUSDVPair(
IERC20 foreignAsset,
IAggregatorV3 oracle,
uint256 updatePeriod
) internal {
require(
updatePeriod != 0,
"LBTWAP::addUSDVPair: Incorrect Update Period"
);
require(oracle.decimals() == 8, "LBTWAP::addUSDVPair: Non-USD Oracle");
oracles[address(foreignAsset)] = oracle;
ExchangePair storage pairData = twapData[address(foreignAsset)];
// NOTE: Redundant
// pairData.foreignAsset = foreignAsset;
pairData.foreignUnit = uint96(
10**uint256(IERC20Metadata(address(foreignAsset)).decimals())
);
pairData.updatePeriod = updatePeriod;
pairData.lastMeasurement = block.timestamp;
(uint256 nativeTokenPriceCumulative, , ) = vaderPool.cumulativePrices(
foreignAsset
);
pairData.nativeTokenPriceCumulative = nativeTokenPriceCumulative;
(uint256 reserveNative, uint256 reserveForeign, ) = vaderPool
.getReserves(foreignAsset);
uint256 pairLiquidityEvaluation = (reserveNative *
previousPrices[uint256(Paths.USDV)]) +
(reserveForeign * getChainlinkPrice(address(foreignAsset)));
pairData.pastLiquidityEvaluation = pairLiquidityEvaluation;
totalLiquidityWeight[uint256(Paths.USDV)] += pairLiquidityEvaluation;
usdvPairs.push(foreignAsset);
if (maxUpdateWindow < updatePeriod) maxUpdateWindow = updatePeriod;
}
} | 3,695 | 493 | 0 | 1. H-03 Oracle doesn't calculate USDV/VADER price correctly in `_calculateVaderPrice`
Invalid values returned from oracle for USDV and VADER prices in situations where the oracle uses more than one foreign asset.
2. H-04 Vader TWAP averages wrong
The vader price in LiquidityBasedTWAP.getVaderPrice is computed using the pastLiquidityWeights and pastTotalLiquidityWeight return values of the syncVaderPrice.
3. H-05 Oracle returns an improperly scaled USDV/VADER price (Price oracle dependence)
The LBT oracle does not properly scale values when calculating prices for VADER or USDV. To show this we consider the simplest case where we expect USDV to return a value of $1 and show that the oracle does not return this value.
4. H-10: previousPrices Is Never Updated Upon Syncing Token Price
The LiquidityBasedTWAP contract attempts to accurately track the price of VADER and USDV while still being resistant to flash loan manipulation and short-term volatility. The previousPrices array is meant to track the last queried price for the two available paths, namely VADER and USDV.
5. M-02: Adding pair of the same foreignAsset would replace oracle of earlier entry in `_addVaderPair`
Oracles are mapped to the foreignAsset but not to the specific pair. Pairs with the same foreignAsset (e.g. UniswapV2 and Sushi) will be forced to use the same oracle. Generally this should be the expected behavior but there are also possibility that while adding a new pair changed the oracle of an older pair unexpectedly.
6. M-06 Oracle can be manipulted to consider only a single pair for pricing in ` _updateUSDVPrice` (Price manipulation)
Loss of resilience of oracle to a faulty pricing for a single pair. In the oracle we calculate the TVL of each pool by pulling the reserves and multiplying both assets by the result of a supposedly manipulation resistant oracle (the oracle queries its previous value for USDV and pulls the foreign asset from chainlink). | 6 |
20_Pool.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
import "./interfaces/iBEP20.sol";
import "./interfaces/iUTILS.sol";
import "./interfaces/iDAO.sol";
import "./interfaces/iBASE.sol";
import "./interfaces/iDAOVAULT.sol";
import "./interfaces/iROUTER.sol";
import "./interfaces/iSYNTH.sol";
import "./interfaces/iSYNTHFACTORY.sol";
import "./interfaces/iBEP677.sol";
contract Pool is iBEP20 {
address public BASE;
address public TOKEN;
address public DEPLOYER;
string _name; string _symbol;
uint8 public override decimals; uint256 public override totalSupply;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint256 public baseAmount;
uint256 public tokenAmount;
uint private lastMonth;
uint public genesis;
uint256 public map30DPoolRevenue;
uint256 public mapPast30DPoolRevenue;
uint256 [] public revenueArray;
event AddLiquidity(address indexed member, uint inputBase, uint inputToken, uint unitsIssued);
event RemoveLiquidity(address indexed member, uint outputBase, uint outputToken, uint unitsClaimed);
event Swapped(address indexed tokenFrom, address indexed tokenTo, address indexed recipient, uint inputAmount, uint outputAmount, uint fee);
event MintSynth(address indexed member, address indexed base, uint256 baseAmount, address indexed token, uint256 synthAmount);
event BurnSynth(address indexed member, address indexed base, uint256 baseAmount, address indexed token, uint256 synthAmount);
function _DAO() internal view returns(iDAO) {
return iBASE(BASE).DAO();
}
constructor (address _base, address _token) {
BASE = _base;
TOKEN = _token;
string memory poolName = "-SpartanProtocolPool";
string memory poolSymbol = "-SPP";
_name = string(abi.encodePacked(iBEP20(_token).name(), poolName));
_symbol = string(abi.encodePacked(iBEP20(_token).symbol(), poolSymbol));
decimals = 18;
genesis = block.timestamp;
DEPLOYER = msg.sender;
lastMonth = 0;
}
//========================================iBEP20=========================================//
function name() external view override returns (string memory) {
return _name;
}
function symbol() external view override returns (string memory) {
return _symbol;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function transfer(address recipient, uint256 amount) external virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) external virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender]+(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "!approval");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "!owner");
require(spender != address(0), "!spender");
if (_allowances[owner][spender] < type(uint256).max) {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
function transferFrom(address sender, address recipient, uint256 amount) external virtual override returns (bool) {
_transfer(sender, recipient, amount);
// Max approval (saves an SSTORE)
if (_allowances[sender][msg.sender] < type(uint256).max) {
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "!approval");
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
//iBEP677 approveAndCall
function approveAndCall(address recipient, uint amount, bytes calldata data) external returns (bool) {
_approve(msg.sender, recipient, type(uint256).max);
// Give recipient max approval
iBEP677(recipient).onTokenApproval(address(this), amount, msg.sender, data);
// Amount is passed thru to recipient
return true;
}
//iBEP677 transferAndCall
function transferAndCall(address recipient, uint amount, bytes calldata data) external returns (bool) {
_transfer(msg.sender, recipient, amount);
iBEP677(recipient).onTokenTransfer(address(this), amount, msg.sender, data);
// Amount is passed thru to recipient
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "!sender");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "!balance");
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "!account");
totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function burn(uint256 amount) external virtual override {
_burn(msg.sender, amount);
}
function burnFrom(address account, uint256 amount) external virtual {
uint256 decreasedAllowance = allowance(account, msg.sender) - (amount);
_approve(account, msg.sender, decreasedAllowance);
_burn(account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "!account");
require(_balances[account] >= amount, "!balance");
_balances[account] -= amount;
totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
//====================================POOL FUNCTIONS =================================//
// User adds liquidity to the pool
function add() external returns(uint liquidityUnits){
liquidityUnits = addForMember(msg.sender);
return liquidityUnits;
}
// Contract adds liquidity for user
function addForMember(address member) public returns(uint liquidityUnits){
uint256 _actualInputBase = _getAddedBaseAmount();
// Get the received SPARTA amount
uint256 _actualInputToken = _getAddedTokenAmount();
// Get the received TOKEN amount
if(baseAmount == 0 || tokenAmount == 0){
require(_actualInputBase != 0 && _actualInputToken != 0, "!Balanced");
}
liquidityUnits = iUTILS(_DAO().UTILS()).calcLiquidityUnits(_actualInputBase, baseAmount, _actualInputToken, tokenAmount, totalSupply);
// Calculate LP tokens to mint
_incrementPoolBalances(_actualInputBase, _actualInputToken);
// Update recorded BASE and TOKEN amounts
_mint(member, liquidityUnits);
// Mint the LP tokens directly to the user
emit AddLiquidity(member, _actualInputBase, _actualInputToken, liquidityUnits);
return liquidityUnits;
}
// User removes liquidity from the pool
function remove() external returns (uint outputBase, uint outputToken) {
return removeForMember(msg.sender);
}
// Contract removes liquidity for the user
function removeForMember(address member) public returns (uint outputBase, uint outputToken) {
uint256 _actualInputUnits = balanceOf(address(this));
// Get the received LP units amount
outputBase = iUTILS(_DAO().UTILS()).calcLiquidityHoldings(_actualInputUnits, BASE, address(this));
// Get the SPARTA value of LP units
outputToken = iUTILS(_DAO().UTILS()).calcLiquidityHoldings(_actualInputUnits, TOKEN, address(this));
// Get the TOKEN value of LP units
_decrementPoolBalances(outputBase, outputToken);
// Update recorded BASE and TOKEN amounts
_burn(address(this), _actualInputUnits);
// Burn the LP tokens
iBEP20(BASE).transfer(member, outputBase);
// Transfer the SPARTA to user
iBEP20(TOKEN).transfer(member, outputToken);
// Transfer the TOKENs to user
emit RemoveLiquidity(member, outputBase, outputToken, _actualInputUnits);
return (outputBase, outputToken);
}
// Caller swaps tokens
function swap(address token) external returns (uint outputAmount, uint fee){
(outputAmount, fee) = swapTo(token, msg.sender);
return (outputAmount, fee);
}
// Contract swaps tokens for the member
function swapTo(address token, address member) public payable returns (uint outputAmount, uint fee) {
require((token == BASE || token == TOKEN), "!BASE||TOKEN");
// Must be SPARTA or the pool's relevant TOKEN
address _fromToken; uint _amount;
if(token == BASE){
_fromToken = TOKEN;
// If SPARTA is selected; swap from TOKEN
_amount = _getAddedTokenAmount();
// Get the received TOKEN amount
(outputAmount, fee) = _swapTokenToBase(_amount);
// Calculate the SPARTA output from the swap
} else {
_fromToken = BASE;
// If TOKEN is selected; swap from SPARTA
_amount = _getAddedBaseAmount();
// Get the received SPARTA amount
(outputAmount, fee) = _swapBaseToToken(_amount);
// Calculate the TOKEN output from the swap
}
emit Swapped(_fromToken, token, member, _amount, outputAmount, fee);
iBEP20(token).transfer(member, outputAmount);
// Transfer the swap output to the selected user
return (outputAmount, fee);
}
// Swap SPARTA for Synths
function mintSynth(address synthOut, address member) external returns(uint outputAmount, uint fee) {
require(iSYNTHFACTORY(_DAO().SYNTHFACTORY()).isSynth(synthOut) == true, "!synth");
// Must be a valid Synth
uint256 _actualInputBase = _getAddedBaseAmount();
// Get received SPARTA amount
uint output = iUTILS(_DAO().UTILS()).calcSwapOutput(_actualInputBase, baseAmount, tokenAmount);
// Calculate value of swapping SPARTA to the relevant underlying TOKEN
uint _liquidityUnits = iUTILS(_DAO().UTILS()).calcLiquidityUnitsAsym(_actualInputBase, address(this));
// Calculate LP tokens to be minted
_incrementPoolBalances(_actualInputBase, 0);
// Update recorded SPARTA amount
uint _fee = iUTILS(_DAO().UTILS()).calcSwapFee(_actualInputBase, baseAmount, tokenAmount);
// Calc slip fee in TOKEN
fee = iUTILS(_DAO().UTILS()).calcSpotValueInBase(TOKEN, _fee);
// Convert TOKEN fee to SPARTA
_mint(synthOut, _liquidityUnits);
// Mint the LP tokens directly to the Synth contract to hold
iSYNTH(synthOut).mintSynth(member, output);
// Mint the Synth tokens directly to the user
_addPoolMetrics(fee);
// Add slip fee to the revenue metrics
emit MintSynth(member, BASE, _actualInputBase, TOKEN, outputAmount);
return (output, fee);
}
// Swap Synths for SPARTA
function burnSynth(address synthIN, address member) external returns(uint outputAmount, uint fee) {
require(iSYNTHFACTORY(_DAO().SYNTHFACTORY()).isSynth(synthIN) == true, "!synth");
// Must be a valid Synth
uint _actualInputSynth = iBEP20(synthIN).balanceOf(address(this));
// Get received SYNTH amount
uint outputBase = iUTILS(_DAO().UTILS()).calcSwapOutput(_actualInputSynth, tokenAmount, baseAmount);
// Calculate value of swapping relevant underlying TOKEN to SPARTA
fee = iUTILS(_DAO().UTILS()).calcSwapFee(_actualInputSynth, tokenAmount, baseAmount);
// Calc slip fee in SPARTA
iBEP20(synthIN).transfer(synthIN, _actualInputSynth);
// Transfer SYNTH to relevant synth contract
iSYNTH(synthIN).burnSynth();
// Burn the SYNTH units
_decrementPoolBalances(outputBase, 0);
// Update recorded SPARTA amount
iBEP20(BASE).transfer(member, outputBase);
// Transfer SPARTA to user
_addPoolMetrics(fee);
// Add slip fee to the revenue metrics
emit BurnSynth(member, BASE, outputBase, TOKEN, _actualInputSynth);
return (outputBase, fee);
}
//=======================================INTERNAL MATHS======================================//
// Check the SPARTA amount received by this Pool
function _getAddedBaseAmount() internal view returns(uint256 _actual){
uint _baseBalance = iBEP20(BASE).balanceOf(address(this));
if(_baseBalance > baseAmount){
_actual = _baseBalance-(baseAmount);
} else {
_actual = 0;
}
return _actual;
}
// Check the TOKEN amount received by this Pool
function _getAddedTokenAmount() internal view returns(uint256 _actual){
uint _tokenBalance = iBEP20(TOKEN).balanceOf(address(this));
if(_tokenBalance > tokenAmount){
_actual = _tokenBalance-(tokenAmount);
} else {
_actual = 0;
}
return _actual;
}
// Calculate output of swapping SPARTA for TOKEN & update recorded amounts
function _swapBaseToToken(uint256 _x) internal returns (uint256 _y, uint256 _fee){
uint256 _X = baseAmount;
uint256 _Y = tokenAmount;
_y = iUTILS(_DAO().UTILS()).calcSwapOutput(_x, _X, _Y);
// Calc TOKEN output
uint fee = iUTILS(_DAO().UTILS()).calcSwapFee(_x, _X, _Y);
// Calc TOKEN fee
_fee = iUTILS(_DAO().UTILS()).calcSpotValueInBase(TOKEN, fee);
// Convert TOKEN fee to SPARTA
_setPoolAmounts(_X + _x, _Y - _y);
// Update recorded BASE and TOKEN amounts
_addPoolMetrics(_fee);
// Add slip fee to the revenue metrics
return (_y, _fee);
}
// Calculate output of swapping TOKEN for SPARTA & update recorded amounts
function _swapTokenToBase(uint256 _x) internal returns (uint256 _y, uint256 _fee){
uint256 _X = tokenAmount;
uint256 _Y = baseAmount;
_y = iUTILS(_DAO().UTILS()).calcSwapOutput(_x, _X, _Y);
// Calc SPARTA output
_fee = iUTILS(_DAO().UTILS()).calcSwapFee(_x, _X, _Y);
// Calc SPARTA fee
_setPoolAmounts(_Y - _y, _X + _x);
// Update recorded BASE and TOKEN amounts
_addPoolMetrics(_fee);
// Add slip fee to the revenue metrics
return (_y, _fee);
}
//=======================================BALANCES=========================================//
// Sync internal balances to actual
function sync() external {
baseAmount = iBEP20(BASE).balanceOf(address(this));
tokenAmount = iBEP20(TOKEN).balanceOf(address(this));
}
// Increment internal balances
function _incrementPoolBalances(uint _baseAmount, uint _tokenAmount) internal {
baseAmount += _baseAmount;
tokenAmount += _tokenAmount;
}
// Set internal balances
function _setPoolAmounts(uint256 _baseAmount, uint256 _tokenAmount) internal {
baseAmount = _baseAmount;
tokenAmount = _tokenAmount;
}
// Decrement internal balances
function _decrementPoolBalances(uint _baseAmount, uint _tokenAmount) internal {
baseAmount -= _baseAmount;
tokenAmount -= _tokenAmount;
}
//===========================================POOL FEE ROI=================================//
function _addPoolMetrics(uint256 _fee) internal {
if(lastMonth == 0){
lastMonth = block.timestamp;
}
if(block.timestamp <= lastMonth + 2592000){
// 30Days
map30DPoolRevenue = map30DPoolRevenue+(_fee);
} else {
lastMonth = block.timestamp;
mapPast30DPoolRevenue = map30DPoolRevenue;
addRevenue(mapPast30DPoolRevenue);
map30DPoolRevenue = 0;
map30DPoolRevenue = map30DPoolRevenue+(_fee);
}
}
function addRevenue(uint _totalRev) internal {
if(!(revenueArray.length == 2)){
revenueArray.push(_totalRev);
} else {
addFee(_totalRev);
}
}
function addFee(uint _rev) internal {
uint _n = revenueArray.length;
// 2
for (uint i = _n - 1; i > 0; i--) {
revenueArray[i] = revenueArray[i - 1];
}
revenueArray[0] = _rev;
}
} | 4,067 | 418 | 0 | 1. [H-02]: Pool.sol & Synth.sol: Failing Max Value Allowance (Lack of input validation)
In the _approve function and `approveAndCall`, if the allowance passed in is type(uint256).max, nothing happens (ie. allowance will still remain at previous value). Contract integrations (DEXes for example) tend to hardcode this value to set maximum allowance initially, but this will result in zero allowance given instead.
| 1 |
20_Synth.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
import "./Pool.sol";
import "./interfaces/iPOOLFACTORY.sol";
contract Synth is iBEP20 {
address public BASE;
address public LayerONE;
// Underlying relevant layer1 token
uint public genesis;
address public DEPLOYER;
string _name; string _symbol;
uint8 public override decimals; uint256 public override totalSupply;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
mapping(address => uint) public mapSynth_LPBalance;
mapping(address => uint) public mapSynth_LPDebt;
function _DAO() internal view returns(iDAO) {
return iBASE(BASE).DAO();
}
// Restrict access
modifier onlyDAO() {
require(msg.sender == DEPLOYER, "!DAO");
_;
}
// Restrict access
modifier onlyPool() {
require(iPOOLFACTORY(_DAO().POOLFACTORY()).isCuratedPool(msg.sender) == true, "!curated");
_;
}
constructor (address _base, address _token) {
BASE = _base;
LayerONE = _token;
string memory synthName = "-SpartanProtocolSynthetic";
string memory synthSymbol = "-SPS";
_name = string(abi.encodePacked(iBEP20(_token).name(), synthName));
_symbol = string(abi.encodePacked(iBEP20(_token).symbol(), synthSymbol));
decimals = iBEP20(_token).decimals();
DEPLOYER = msg.sender;
genesis = block.timestamp;
}
//========================================iBEP20=========================================//
function name() external view override returns (string memory) {
return _name;
}
function symbol() external view override returns (string memory) {
return _symbol;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
// iBEP20 Transfer function
function transfer(address recipient, uint256 amount) external virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
// iBEP20 Approve, change allowance functions
function approve(address spender, uint256 amount) external virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender]+(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "!approval");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "!owner");
require(spender != address(0), "!spender");
if (_allowances[owner][spender] < type(uint256).max) {
// No need to re-approve if already max
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// iBEP20 TransferFrom function
function transferFrom(address sender, address recipient, uint256 amount) external virtual override returns (bool) {
_transfer(sender, recipient, amount);
// Unlimited approval (saves an SSTORE)
if (_allowances[sender][msg.sender] < type(uint256).max) {
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "!approval");
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
//iBEP677 approveAndCall
function approveAndCall(address recipient, uint amount, bytes calldata data) external returns (bool) {
_approve(msg.sender, recipient, type(uint256).max);
// Give recipient max approval
iBEP677(recipient).onTokenApproval(address(this), amount, msg.sender, data);
// Amount is passed thru to recipient
return true;
}
//iBEP677 transferAndCall
function transferAndCall(address recipient, uint amount, bytes calldata data) external returns (bool) {
_transfer(msg.sender, recipient, amount);
iBEP677(recipient).onTokenTransfer(address(this), amount, msg.sender, data);
// Amount is passed thru to recipient
return true;
}
// Internal transfer function
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "!sender");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "!balance");
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
// Internal mint (upgrading and daily emissions)
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "!account");
totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
// Burn supply
function burn(uint256 amount) external virtual override {
_burn(msg.sender, amount);
}
function burnFrom(address account, uint256 amount) external virtual {
uint256 decreasedAllowance = allowance(account, msg.sender) - (amount);
_approve(account, msg.sender, decreasedAllowance);
_burn(account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "!account");
require(_balances[account] >= amount, "!balance");
_balances[account] -= amount;
totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
//==================================== SYNTH FUNCTIONS =================================//
// Handle received LP tokens and mint Synths
function mintSynth(address member, uint amount) external onlyPool returns (uint syntheticAmount){
uint lpUnits = _getAddedLPAmount(msg.sender);
// Get the received LP units
mapSynth_LPDebt[msg.sender] += amount;
// Increase debt by synth amount
mapSynth_LPBalance[msg.sender] += lpUnits;
// Increase lp balance by LPs received
_mint(member, amount);
// Mint the synths & tsf to user
return amount;
}
// Handle received Synths and burn the LPs and Synths
function burnSynth() external returns (bool){
uint _syntheticAmount = balanceOf(address(this));
// Get the received synth units
uint _amountUnits = (_syntheticAmount * mapSynth_LPBalance[msg.sender]) / mapSynth_LPDebt[msg.sender];
// share = amount * part/total
mapSynth_LPBalance[msg.sender] -= _amountUnits;
// Reduce lp balance
mapSynth_LPDebt[msg.sender] -= _syntheticAmount;
// Reduce debt by synths being burnt
if(_amountUnits > 0){
_burn(address(this), _syntheticAmount);
// Burn the synths
Pool(msg.sender).burn(_amountUnits);
// Burn the LP tokens
}
return true;
}
// Burn LPs to if their value outweights the synths supply value (Ensures incentives are funnelled to existing LPers)
function realise(address pool) external {
uint baseValueLP = iUTILS(_DAO().UTILS()).calcLiquidityHoldings(mapSynth_LPBalance[pool], BASE, pool);
// Get the SPARTA value of the LP tokens
uint baseValueSynth = iUTILS(_DAO().UTILS()).calcActualSynthUnits(mapSynth_LPDebt[pool], address(this));
// Get the SPARTA value of the synths
if(baseValueLP > baseValueSynth){
uint premium = baseValueLP - baseValueSynth;
// Get the premium between the two values
if(premium > 10**18){
uint premiumLP = iUTILS(_DAO().UTILS()).calcLiquidityUnitsAsym(premium, pool);
// Get the LP value of the premium
mapSynth_LPBalance[pool] -= premiumLP;
// Reduce the LP balance
Pool(pool).burn(premiumLP);
// Burn the premium of the LP tokens
}
}
}
// Check the received token amount
function _handleTransferIn(address _token, uint256 _amount) internal returns(uint256 _actual){
if(_amount > 0) {
uint startBal = iBEP20(_token).balanceOf(address(this));
// Get existing balance
iBEP20(_token).transferFrom(msg.sender, address(this), _amount);
// Transfer tokens in
_actual = iBEP20(_token).balanceOf(address(this)) - startBal;
// Calculate received amount
}
return _actual;
}
// Check the received LP tokens amount
function _getAddedLPAmount(address _pool) internal view returns(uint256 _actual){
uint _lpCollateralBalance = iBEP20(_pool).balanceOf(address(this));
// Get total balance held
if(_lpCollateralBalance > mapSynth_LPBalance[_pool]){
_actual = _lpCollateralBalance - mapSynth_LPBalance[_pool];
// Get received amount
} else {
_actual = 0;
}
return _actual;
}
function getmapAddress_LPBalance(address pool) external view returns (uint){
return mapSynth_LPBalance[pool];
}
function getmapAddress_LPDebt(address pool) external view returns (uint){
return mapSynth_LPDebt[pool];
}
} | 2,248 | 255 | 0 | 1. H-02: Pool.sol & Synth.sol: Failing Max Value Allowance (Lack of input validation)
In the `_approve` function, if the allowance passed in is `type(uint256).max`, nothing happens (ie. allowance will still remain at previous value). Contract integrations (DEXes for example) tend to hardcode this value to set maximum allowance initially, but this will result in zero allowance given instead
2. H-05: Synth realise is vulnerable to flash loan attacks (Flash loan, Price manipulation)
Synth `realise` function calculates `baseValueLP` and `baseValueSynth` base on AMM spot price which is vulnerable to flash loan attack. `Synth`'s lp is subject to `realise` whenever the AMM ratio is different than Synth's debt ratio. | 2 |
83_Shelter.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IShelter } from "./interfaces/IShelter.sol";
import { IShelterClient } from "./interfaces/IShelterClient.sol";
contract Shelter is IShelter {
using SafeERC20 for IERC20;
IShelterClient public immutable client;
uint256 public constant GRACE_PERIOD = 1 weeks;
mapping(IERC20 => mapping(address => bool)) public override claimed;
mapping(IERC20 => uint256) public activated;
mapping(IERC20 => uint256) public savedTokens;
modifier onlyClient {
require(msg.sender == address(client), "!client");
_;
}
constructor(IShelterClient _client){
client = _client;
}
function donate(IERC20 _token, uint256 _amount) external {
require(activated[_token] != 0, "!activated");
savedTokens[_token] += _amount;
_token.safeTransferFrom(msg.sender, address(this), _amount);
}
function activate(IERC20 _token) external override onlyClient {
activated[_token] = block.timestamp;
savedTokens[_token] = _token.balanceOf(address(this));
emit ShelterActivated(_token);
}
function deactivate(IERC20 _token) external override onlyClient {
require(activated[_token] != 0 && activated[_token] + GRACE_PERIOD > block.timestamp, "too late");
activated[_token] = 0;
savedTokens[_token] = 0;
_token.safeTransfer(msg.sender, _token.balanceOf(address(this)));
emit ShelterDeactivated(_token);
}
function withdraw(IERC20 _token, address _to) external override {
require(activated[_token] != 0 && activated[_token] + GRACE_PERIOD < block.timestamp, "shelter not activated");
uint256 amount = savedTokens[_token] * client.shareOf(_token, msg.sender) / client.totalShare(_token);
claimed[_token][_to] = true;
emit ExitShelter(_token, msg.sender, _to, amount);
_token.safeTransfer(_to, amount);
}
} | 511 | 60 | 1 | 1. [H-03] Repeated Calls to Shelter.withdraw Can Drain All Funds in Shelter (L52-L57) (Reentrancy)
Anyone who can call `withdraw` to withdraw their own funds can call it repeatedly to withdraw the funds of others. withdraw should only succeed if the user hasn't withdrawn the token already.
2. [H-07] Shelter claimed mapping is set with _to address and not msg.sender L55 (wrong input address)
Even if the `claimed` mapping was checked, there would still be a vulnerability. This is because the claimed mapping is updated with the _to address, not the msg.sender address.
3. [M-01] Deposits after the grace period should not be allowed. (Claim management)
Function `donate` in Shelter shouldn't allow new deposits after the grace period ends, when the claim period begins.
`savedTokens[_token] += _amount;`. `donate` and `withdraw`
`uint256 amount = savedTokens[_token] * client.shareOf(_token, msg.sender) / client.totalShare(_token);`
4. [M-07]: Fee-on-transfer token donations in Shelter break withdrawals (Unsafe Transfer)
The Sheler.donate function transferFroms _amount and adds the entire _amount to savedTokens[_token].
5. [M-08] Donated Tokens Cannot Be Recovered If A Shelter Is Deactivated L32-L36
The shelter mechanism can be activated and deactivated on a target LP token. The owner of the ConvexStakingWrapper.sol contract can initiate the shelter whereby LP tokens are sent to the Shelter.sol contract. `donate` function | 5 |
107_yVault.sol | // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../interfaces/IController.sol";
import "../../interfaces/IYVault.sol";
/// @title JPEG'd yVault
/// @notice Allows users to deposit fungible assets into autocompounding strategy contracts (e.g. {StrategyPUSDConvex}).
/// Non whitelisted contracts can't deposit/withdraw.
/// Owner is DAO
contract YVault is ERC20, Ownable {
using SafeERC20 for ERC20;
using Address for address;
event Deposit(address indexed depositor, uint256 wantAmount);
event Withdrawal(address indexed withdrawer, uint256 wantAmount);
struct Rate {
uint128 numerator;
uint128 denominator;
}
ERC20 public immutable token;
IController public controller;
address public farm;
Rate internal availableTokensRate;
mapping(address => bool) public whitelistedContracts;
/// @param _token The token managed by this vault
/// @param _controller The JPEG'd strategies controller
constructor(
address _token,
address _controller,
Rate memory _availableTokensRate
)
ERC20(
string(
abi.encodePacked("JPEG\xE2\x80\x99d ", ERC20(_token).name())
),
string(abi.encodePacked("JPEGD", ERC20(_token).symbol()))
)
{
setController(_controller);
setAvailableTokensRate(_availableTokensRate);
token = ERC20(_token);
}
/// @dev Modifier that ensures that non-whitelisted contracts can't interact with the vault.
/// Prevents non-whitelisted 3rd party contracts from diluting stakers.
/// The {isContract} function returns false when `_account` is a contract executing constructor code.
/// This may lead to some contracts being able to bypass this check.
/// @param _account Address to check
modifier noContract(address _account) {
require(
!_account.isContract() || whitelistedContracts[_account],
"Contracts not allowed"
);
_;
}
/// @inheritdoc ERC20
function decimals() public view virtual override returns (uint8) {
return token.decimals();
}
/// @return The total amount of tokens managed by this vault and the underlying strategy
function balance() public view returns (uint256) {
return
token.balanceOf(address(this)) +
controller.balanceOf(address(token));
}
// @return The amount of JPEG tokens claimable by {YVaultLPFarming}
function balanceOfJPEG() external view returns (uint256) {
return controller.balanceOfJPEG(address(token));
}
/// @notice Allows the owner to whitelist/blacklist contracts
/// @param _contract The contract address to whitelist/blacklist
/// @param _isWhitelisted Whereter to whitelist or blacklist `_contract`
function setContractWhitelisted(address _contract, bool _isWhitelisted)
external
onlyOwner
{
whitelistedContracts[_contract] = _isWhitelisted;
}
/// @notice Allows the owner to set the rate of tokens held by this contract that the underlying strategy should be able to borrow
/// @param _rate The new rate
function setAvailableTokensRate(Rate memory _rate) public onlyOwner {
require(
_rate.numerator > 0 && _rate.denominator >= _rate.numerator,
"INVALID_RATE"
);
availableTokensRate = _rate;
}
/// @notice ALlows the owner to set this vault's controller
/// @param _controller The new controller
function setController(address _controller) public onlyOwner {
require(_controller != address(0), "INVALID_CONTROLLER");
controller = IController(_controller);
}
/// @notice Allows the owner to set the yVault LP farm
/// @param _farm The new farm
function setFarmingPool(address _farm) public onlyOwner {
require(_farm != address(0), "INVALID_FARMING_POOL");
farm = _farm;
}
/// @return How much the vault allows to be borrowed by the underlying strategy.
/// Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint256) {
return
(token.balanceOf(address(this)) * availableTokensRate.numerator) /
availableTokensRate.denominator;
}
/// @notice Deposits `token` into the underlying strategy
function earn() external {
uint256 _bal = available();
token.safeTransfer(address(controller), _bal);
controller.earn(address(token), _bal);
}
/// @notice Allows users to deposit their entire `token` balance
function depositAll() external {
deposit(token.balanceOf(msg.sender));
}
/// @notice Allows users to deposit `token`. Contracts can't call this function
/// @param _amount The amount to deposit
function deposit(uint256 _amount) public noContract(msg.sender) {
require(_amount > 0, "INVALID_AMOUNT");
uint256 balanceBefore = balance();
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 supply = totalSupply();
uint256 shares;
if (supply == 0) {
shares = _amount;
} else {
//balanceBefore can't be 0 if totalSupply is > 0
shares = (_amount * supply) / balanceBefore;
}
_mint(msg.sender, shares);
emit Deposit(msg.sender, _amount);
}
/// @notice Allows users to withdraw all their deposited balance
function withdrawAll() external {
withdraw(balanceOf(msg.sender));
}
/// @notice Allows users to withdraw tokens. Contracts can't call this function
/// @param _shares The amount of shares to burn
function withdraw(uint256 _shares) public noContract(msg.sender) {
require(_shares > 0, "INVALID_AMOUNT");
uint256 supply = totalSupply();
require(supply > 0, "NO_TOKENS_DEPOSITED");
uint256 backingTokens = (balance() * _shares) / supply;
_burn(msg.sender, _shares);
// Check balance
uint256 vaultBalance = token.balanceOf(address(this));
if (vaultBalance < backingTokens) {
uint256 toWithdraw = backingTokens - vaultBalance;
controller.withdraw(address(token), toWithdraw);
}
token.safeTransfer(msg.sender, backingTokens);
emit Withdrawal(msg.sender, backingTokens);
}
/// @notice Allows anyone to withdraw JPEG to `farm`
function withdrawJPEG() external {
require(farm != address(0), "NO_FARM");
controller.withdrawJPEG(address(token), farm);
}
/// @return The underlying tokens per share
function getPricePerFullShare() external view returns (uint256) {
uint256 supply = totalSupply();
if (supply == 0) return 0;
return (balance() * 1e18) / supply;
}
/// @dev Prevent the owner from renouncing ownership. Having no owner would render this contract unusable due to the inability to create new epochs
function renounceOwnership() public view override onlyOwner {
revert("Cannot renounce ownership");
}
} | 1,617 | 204 | 1 | 1. [H-01] yVault: First depositor can break minting of shares L148-L153 in `deposit` function
The attack vector and impact is the same as TOB-YEARN-003, where users may not receive shares in exchange for their deposits if the total asset amount has been manipulated through a large “donation”.
2. [H-04] Reentrancy issue in yVault.deposit (reentrancy)
In deposit, the balance is cached and then a token.transferFrom is triggered which can lead to exploits if the token is a token that gives control to the sender, like ERC777 tokens.
3. [H-06] Setting new controller can break YVaultLPFarming L108
The currentBalance < previousBalance case can, for example, be triggerd by decreasing the vault.balanceOfJPEG() due to calling `yVault.setController`
4. [M-07] Wrong calculation for yVault price per share if decimals != 18.
The yVault.getPricePerFullShare() function calculates the price per share by multiplying with 1e18 token decimals with the assumption that the underlying token always has 18 decimals. yVault has the same amount of decimals as it's underlying token see (yVault.decimals())
5. [M-09] The noContract modifier does not work as expected.
The expectation of the `noContract` modifier is to allow access only to accounts inside EOA or Whitelist, if access is controlled using ! access control with _account.isContract(), then because isContract() gets the size of the code length of the account in question by relying on extcodesize/address.code.length, this means that the restriction can be bypassed when deploying a smart contract through the smart contract's constructor call. | 5 |
66_sYETIToken.sol | //SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./BoringCrypto/BoringMath.sol";
import "./BoringCrypto/BoringERC20.sol";
import "./BoringCrypto/Domain.sol";
import "./BoringCrypto/ERC20.sol";
import "./BoringCrypto/IERC20.sol";
import "./BoringCrypto/BoringOwnable.sol";
import "./IsYETIRouter.sol";
interface IYETIToken is IERC20 {
function sendToSYETI(address _sender, uint256 _amount) external;
function transfer(address recipient, uint256 amount) external returns (bool);
}
// Staking in sSpell inspired by Chef Nomi's SushiBar - MIT license (originally WTFPL)
// modified by BoringCrypto for DictatorDAO
// Use effective yetibalance, which updates on rebase. Rebase occurs every 8
// Each rebase increases the effective yetibalance by a certain amount of the total value
// of the contract, which is equal to the yusd balance + the last price which the buyback
// was executed at, multiplied by the YETI balance. Then, a portion of the value, say 1/200
// of the total value of the contract is added to the effective yetibalance. Also updated on
// mint and withdraw, because that is actual value that is added to the contract.
contract sYETIToken is IERC20, Domain, BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
string public constant symbol = "sYETI";
string public constant name = "Staked YETI Tokens";
uint8 public constant decimals = 18;
uint256 public override totalSupply;
uint256 private constant LOCK_TIME = 69 hours;
uint256 public effectiveYetiTokenBalance;
uint256 public lastBuybackTime;
uint256 public lastBuybackPrice;
uint256 public lastRebaseTime;
uint256 public transferRatio;
// 100% = 1e18. Amount to transfer over each rebase.
IYETIToken public yetiToken;
IERC20 public yusdToken;
bool private addressesSet;
// Internal mapping to keep track of valid routers. Find the one with least slippage off chain
// and do that one.
mapping(address => bool) public validRouters;
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event BuyBackExecuted(uint YUSDToSell, uint amounts0, uint amounts1);
event Rebase(uint additionalYetiTokenBalance);
function balanceOf(address user) public view override returns (uint256) {
return users[user].balance;
}
function setAddresses(IYETIToken _yeti, IERC20 _yusd) external onlyOwner {
require(!addressesSet, "addresses already set");
yetiToken = _yeti;
yusdToken = _yusd;
addressesSet = true;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address");
// Moved down so other failed calls safe some gas
User memory toUser = users[to];
uint128 shares128 = shares.to128();
users[from].balance = fromUser.balance - shares128;
// Underflow is checked
users[to].balance = toUser.balance + shares128;
// Can't overflow because totalSupply would be greater than 2^128-1;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
uint256 newAllowance = spenderAllowance - shares;
allowance[from][msg.sender] = newAllowance;
// Underflow is checked
emit Approval(from, msg.sender, newAllowance);
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function increaseAllowance(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] += amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount) public returns (bool) {
User memory user = users[msg.sender];
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / effectiveYetiTokenBalance;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + LOCK_TIME).to128();
users[msg.sender] = user;
totalSupply += shares;
yetiToken.sendToSYETI(msg.sender, amount);
effectiveYetiTokenBalance = effectiveYetiTokenBalance.add(amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * effectiveYetiTokenBalance) / totalSupply;
users[from].balance = user.balance.sub(shares.to128());
// Must check underflow
totalSupply -= shares;
yetiToken.transfer(to, amount);
effectiveYetiTokenBalance = effectiveYetiTokenBalance.sub(amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
/**
* Buyback function called by owner of function. Keeps track of the
*/
function buyBack(address _routerAddress, uint256 _YUSDToSell, uint256 _YETIOutMin) external onlyOwner {
require(_YUSDToSell != 0, "Zero amount");
require(yusdToken.balanceOf(address(this)) >= _YUSDToSell, "Not enough YUSD in contract");
_buyBack(_routerAddress, _YUSDToSell, _YETIOutMin);
}
/**
* Public function for doing buybacks, eligible every 169 hours. This is so that there are some guaranteed rewards to be distributed if the team multisig is lost.
* Has a max amount of YUSD to sell at 5% of the YUSD in the contract, which should be enough to cover the amount. Uses the default router which has a time lock
* in order to activate.
* No YUSDToSell param since this just does 5% of the YUSD in the contract.
*/
function publicBuyBack(address _routerAddress) external {
uint256 YUSDBalance = yusdToken.balanceOf(address(this));
require(YUSDBalance != 0, "No YUSD in contract");
require(lastBuybackTime + 169 hours < block.timestamp, "Can only publicly buy back every 169 hours");
// Get 5% of the YUSD in the contract
// Always enough YUSD in the contract to cover the 5% of the YUSD in the contract
uint256 YUSDToSell = div(YUSDBalance.mul(5), 100);
_buyBack(_routerAddress, YUSDToSell, 0);
}
// Internal function calls the router function for buyback and emits event with amount of YETI bought and YUSD spent.
function _buyBack(address _routerAddress, uint256 _YUSDToSell, uint256 _YETIOutMin) internal {
// Checks internal mapping to see if router is valid
require(validRouters[_routerAddress] == true, "Invalid router passed in");
require(yusdToken.approve(_routerAddress, 0));
require(yusdToken.increaseAllowance(_routerAddress, _YUSDToSell));
lastBuybackTime = block.timestamp;
uint256[] memory amounts = IsYETIRouter(_routerAddress).swap(_YUSDToSell, _YETIOutMin, address(this));
// amounts[0] is the amount of YUSD that was sold, and amounts[1] is the amount of YETI that was gained in return. So the price is amounts[0] / amounts[1]
lastBuybackPrice = div(amounts[0].mul(1e18), amounts[1]);
emit BuyBackExecuted(_YUSDToSell, amounts[0], amounts[1]);
}
// Rebase function for adding new value to the sYETI - YETI ratio.
function rebase() external {
require(block.timestamp >= lastRebaseTime + 8 hours, "Can only rebase every 8 hours");
// Use last buyback price to transfer some of the actual YETI Tokens that this contract owns
// to the effective yeti token balance. Transfer a portion of the value over to the effective balance
// raw balance of the contract
uint256 yetiTokenBalance = yetiToken.balanceOf(address(this));
// amount of YETI free / available to give out
uint256 adjustedYetiTokenBalance = yetiTokenBalance.sub(effectiveYetiTokenBalance);
// in YETI, amount that should be eligible to give out.
uint256 valueOfContract = _getValueOfContract(adjustedYetiTokenBalance);
// in YETI, amount to rebase
uint256 amountYetiToRebase = div(valueOfContract.mul(transferRatio), 1e18);
// Ensure that the amount of YETI tokens effectively added is >= the amount we have repurchased.
// Amount available = adjustdYetiTokenBalance, amount to distribute is amountYetiToRebase
if (amountYetiToRebase > adjustedYetiTokenBalance) {
amountYetiToRebase = adjustedYetiTokenBalance;
}
// rebase amount joins the effective supply.
effectiveYetiTokenBalance = effectiveYetiTokenBalance.add(amountYetiToRebase);
// update rebase time
lastRebaseTime = block.timestamp;
emit Rebase(amountYetiToRebase);
}
// Sums YUSD balance + old price.
// Should take add the YUSD balance / last buyback price to get value of the YUSD in YETI
// added to the YETI balance of the contract. Essentially the amount it is eligible to give out.
function _getValueOfContract(uint _adjustedYetiTokenBalance) internal view returns (uint256) {
uint256 yusdTokenBalance = yusdToken.balanceOf(address(this));
return div(yusdTokenBalance.mul(1e18), lastBuybackPrice).add(_adjustedYetiTokenBalance);
}
// Sets new transfer ratio for rebasing
function setTransferRatio(uint256 newTransferRatio) external onlyOwner {
require(newTransferRatio != 0, "Zero transfer ratio");
require(newTransferRatio <= 1e18, "Transfer ratio too high");
transferRatio = newTransferRatio;
}
// TODO - add time delay for setting new valid router.
function addValidRouter(address _routerAddress) external onlyOwner {
require(_routerAddress != address(0), "Invalid router address");
validRouters[_routerAddress] = true;
}
// TODO - add time delay for invalidating router.
function removeValidRouter(address _routerAddress) external onlyOwner {
validRouters[_routerAddress] = false;
}
// Safe divide
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b != 0, "BoringMath: Div By 0");
return a / b;
}
} | 3,607 | 345 | 1 | 1. [H-02] Yeti token rebase checks the additional token amount incorrectly (Timestamp manipulation)
The condition isn't checked now as the whole balance is used instead of the Yeti tokens bought back from the market. As it's not checked, the amount added to `effectiveYetiTokenBalance` during rebase can exceed the actual amount of the Yeti tokens owned by the contract. As the before check amount is calculated as the contract net worth, it can be fixed by immediate buy back, but it will not be the case.
2. [M-01] Wrong lastBuyBackPrice (Price manipulation)
The `sYETIToken.lastBuyBackPrice` is set in `buyBack` and hardcoded as: It divides the first and second return amounts of the swap, however, these amounts depend on the swap path parameter that is used by the caller. If a swap path of length 3 is used, then this is obviously wrong. It also assumes that each router sorts the pairs the same way (which is true for Uniswap/Sushiswap). | 2 |
20_synthVault.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
import "./interfaces/iBEP20.sol";
import "./interfaces/iDAO.sol";
import "./interfaces/iBASE.sol";
import "./interfaces/iPOOL.sol";
import "./interfaces/iSYNTH.sol";
import "./interfaces/iUTILS.sol";
import "./interfaces/iRESERVE.sol";
import "./interfaces/iSYNTHFACTORY.sol";
import "./interfaces/iPOOLFACTORY.sol";
contract SynthVault {
address public BASE;
address public DEPLOYER;
uint256 public minimumDepositTime;
// Withdrawal & Harvest lockout period; intended to be 1 hour
uint256 public totalWeight;
// Total weight of the whole SynthVault
uint256 public erasToEarn;
// Amount of eras that make up the targeted RESERVE depletion; regulates incentives
uint256 public vaultClaim;
// The SynthVaults's portion of rewards; intended to be ~10% initially
address [] public stakedSynthAssets;
// Array of all synth assets that have ever been staked in (scope: vault)
uint private lastMonth;
// Timestamp of the start of current metric period (For UI)
uint public genesis;
// Timestamp from when the synth was first deployed (For UI)
uint256 public map30DVaultRevenue;
// Tally of revenue during current incomplete metric period (for UI)
uint256 public mapPast30DVaultRevenue;
// Tally of revenue from last full metric period (for UI)
uint256 [] public revenueArray;
// Array of the last two metric periods (For UI)
// Restrict access
modifier onlyDAO() {
require(msg.sender == _DAO().DAO() || msg.sender == DEPLOYER);
_;
}
constructor(address _base) {
BASE = _base;
DEPLOYER = msg.sender;
erasToEarn = 30;
minimumDepositTime = 3600;
// 1 hour
vaultClaim = 1000;
genesis = block.timestamp;
lastMonth = 0;
}
function _DAO() internal view returns(iDAO) {
return iBASE(BASE).DAO();
}
mapping(address => mapping(address => uint256)) private mapMemberSynth_weight;
mapping(address => uint256) private mapMemberTotal_weight;
mapping(address => mapping(address => uint256)) private mapMemberSynth_deposit;
mapping(address => mapping(address => uint256)) private mapMemberSynth_lastTime;
mapping(address => uint256) private mapMember_depositTime;
mapping(address => uint256) public lastBlock;
mapping(address => bool) private isStakedSynth;
mapping(address => mapping(address => bool)) private isSynthMember;
event MemberDeposits(
address indexed synth,
address indexed member,
uint256 newDeposit,
uint256 weight,
uint256 totalWeight
);
event MemberWithdraws(
address indexed synth,
address indexed member,
uint256 amount,
uint256 weight,
uint256 totalWeight
);
event MemberHarvests(
address indexed synth,
address indexed member,
uint256 amount,
uint256 weight,
uint256 totalWeight
);
function setParams(uint256 one, uint256 two, uint256 three) external onlyDAO {
erasToEarn = one;
minimumDepositTime = two;
vaultClaim = three;
}
//====================================== DEPOSIT ========================================//
// User deposits Synths in the SynthVault
function deposit(address synth, uint256 amount) external {
depositForMember(synth, msg.sender, amount);
}
// Contract deposits Synths in the SynthVault for user
function depositForMember(address synth, address member, uint256 amount) public {
require(iSYNTHFACTORY(_DAO().SYNTHFACTORY()).isSynth(synth), "!synth");
// Must be a valid synth
require(iBEP20(synth).transferFrom(msg.sender, address(this), amount));
// Must successfuly transfer in
_deposit(synth, member, amount);
// Assess and record the deposit
}
// Check and record the deposit
function _deposit(address _synth, address _member, uint256 _amount) internal {
if(!isStakedSynth[_synth]){
isStakedSynth[_synth] = true;
// Record as a staked synth
stakedSynthAssets.push(_synth);
// Add to staked synth array
}
mapMemberSynth_lastTime[_member][_synth] = block.timestamp + minimumDepositTime;
// Record deposit time (scope: member -> synth)
mapMember_depositTime[_member] = block.timestamp + minimumDepositTime;
// Record deposit time (scope: member)
mapMemberSynth_deposit[_member][_synth] += _amount;
// Record balance for member
uint256 _weight = iUTILS(_DAO().UTILS()).calcSpotValueInBase(iSYNTH(_synth).LayerONE(), _amount);
// Get the SPARTA weight of the deposit
mapMemberSynth_weight[_member][_synth] += _weight;
// Add the weight to the user (scope: member -> synth)
mapMemberTotal_weight[_member] += _weight;
// Add to the user's total weight (scope: member)
totalWeight += _weight;
// Add to the total weight (scope: vault)
isSynthMember[_member][_synth] = true;
// Record user as a member
emit MemberDeposits(_synth, _member, _amount, _weight, totalWeight);
}
//====================================== HARVEST ========================================//
// User harvests all of their available rewards
function harvestAll() external returns (bool) {
for(uint i = 0; i < stakedSynthAssets.length; i++){
if((block.timestamp > mapMemberSynth_lastTime[msg.sender][stakedSynthAssets[i]])){
uint256 reward = calcCurrentReward(stakedSynthAssets[i], msg.sender);
if(reward > 0){
harvestSingle(stakedSynthAssets[i]);
}
}
}
return true;
}
// User harvests available rewards of the chosen asset
function harvestSingle(address synth) public returns (bool) {
require(iSYNTHFACTORY(_DAO().SYNTHFACTORY()).isSynth(synth), "!synth");
// Must be valid synth
require(iRESERVE(_DAO().RESERVE()).emissions(), "!emissions");
// RESERVE emissions must be on
uint256 _weight;
uint256 reward = calcCurrentReward(synth, msg.sender);
// Calc user's current SPARTA reward
mapMemberSynth_lastTime[msg.sender][synth] = block.timestamp;
// Set last harvest time as now
address _poolOUT = iPOOLFACTORY(_DAO().POOLFACTORY()).getPool(iSYNTH(synth).LayerONE());
// Get pool address
iRESERVE(_DAO().RESERVE()).grantFunds(reward, _poolOUT);
// Send the SPARTA from RESERVE to POOL
(uint synthReward,) = iPOOL(_poolOUT).mintSynth(synth, address(this));
// Mint synths & tsf to SynthVault
_weight = iUTILS(_DAO().UTILS()).calcSpotValueInBase(iSYNTH(synth).LayerONE(), synthReward);
// Calc reward's SPARTA value
mapMemberSynth_deposit[msg.sender][synth] += synthReward;
// Record deposit for the user (scope: member -> synth)
mapMemberSynth_weight[msg.sender][synth] += _weight;
// Add the weight to the user (scope: member -> synth)
mapMemberTotal_weight[msg.sender] += _weight;
// Add to the user's total weight (scope: member)
totalWeight += _weight;
// Add to the total weight (scope: vault)
_addVaultMetrics(reward);
// Add to the revenue metrics (for UI)
iSYNTH(synth).realise(_poolOUT);
// Check synth-held LP value for premium; burn if so
emit MemberHarvests(synth, msg.sender, reward, _weight, totalWeight);
return true;
}
// Calculate the user's current incentive-claim per era based on selected asset
function calcCurrentReward(address synth, address member) public view returns (uint256 reward){
require((block.timestamp > mapMemberSynth_lastTime[member][synth]), "!unlocked");
// Must not harvest before lockup period passed
uint256 _secondsSinceClaim = block.timestamp - mapMemberSynth_lastTime[member][synth];
// Get seconds passed since last claim
uint256 _share = calcReward(synth, member);
// Get member's share of RESERVE incentives
reward = (_share * _secondsSinceClaim) / iBASE(BASE).secondsPerEra();
// User's share times eras since they last claimed
return reward;
}
// Calculate the user's current total claimable incentive
function calcReward(address synth, address member) public view returns (uint256) {
uint256 _weight = mapMemberSynth_weight[member][synth];
// Get user's weight (scope: member -> synth)
uint256 _reserve = reserveBASE() / erasToEarn;
// Aim to deplete reserve over a number of days
uint256 _vaultReward = (_reserve * vaultClaim) / 10000;
// Get the SynthVault's share of that
return iUTILS(_DAO().UTILS()).calcShare(_weight, totalWeight, _vaultReward);
// Get member's share of that
}
//====================================== WITHDRAW ========================================//
// User withdraws a percentage of their synths from the vault
function withdraw(address synth, uint256 basisPoints) external returns (uint256 redeemedAmount) {
redeemedAmount = _processWithdraw(synth, msg.sender, basisPoints);
// Perform the withdrawal
require(iBEP20(synth).transfer(msg.sender, redeemedAmount));
// Transfer from SynthVault to user
return redeemedAmount;
}
// Contract withdraws a percentage of user's synths from the vault
function _processWithdraw(address _synth, address _member, uint256 _basisPoints) internal returns (uint256 synthReward) {
require((block.timestamp > mapMember_depositTime[_member]), "lockout");
// Must not withdraw before lockup period passed
uint256 _principle = iUTILS(_DAO().UTILS()).calcPart(_basisPoints, mapMemberSynth_deposit[_member][_synth]);
// Calc amount to withdraw
mapMemberSynth_deposit[_member][_synth] -= _principle;
// Remove from user's recorded vault holdings
uint256 _weight = iUTILS(_DAO().UTILS()).calcPart(_basisPoints, mapMemberSynth_weight[_member][_synth]);
// Calc SPARTA value of amount
mapMemberTotal_weight[_member] -= _weight;
// Remove from member's total weight (scope: member)
mapMemberSynth_weight[_member][_synth] -= _weight;
// Remove from member's synth weight (scope: member -> synth)
totalWeight -= _weight;
// Remove from total weight (scope: vault)
emit MemberWithdraws(_synth, _member, synthReward, _weight, totalWeight);
return (_principle + synthReward);
}
//================================ Helper Functions ===============================//
function reserveBASE() public view returns (uint256) {
return iBEP20(BASE).balanceOf(_DAO().RESERVE());
}
function getMemberDeposit(address synth, address member) external view returns (uint256){
return mapMemberSynth_deposit[member][synth];
}
function getMemberWeight(address member) external view returns (uint256) {
return mapMemberTotal_weight[member];
}
function getStakeSynthLength() external view returns (uint256) {
return stakedSynthAssets.length;
}
function getMemberLastTime(address member) external view returns (uint256) {
return mapMember_depositTime[member];
}
function getMemberLastSynthTime(address synth, address member) external view returns (uint256){
return mapMemberSynth_lastTime[member][synth];
}
function getMemberSynthWeight(address synth, address member) external view returns (uint256) {
return mapMemberSynth_weight[member][synth];
}
//=============================== SynthVault Metrics =================================//
function _addVaultMetrics(uint256 _fee) internal {
if(lastMonth == 0){
lastMonth = block.timestamp;
}
if(block.timestamp <= lastMonth + 2592000){
// 30 days
map30DVaultRevenue = map30DVaultRevenue + _fee;
} else {
lastMonth = block.timestamp;
mapPast30DVaultRevenue = map30DVaultRevenue;
addRevenue(mapPast30DVaultRevenue);
map30DVaultRevenue = 0;
map30DVaultRevenue = map30DVaultRevenue + _fee;
}
}
function addRevenue(uint _totalRev) internal {
if(!(revenueArray.length == 2)){
revenueArray.push(_totalRev);
} else {
addFee(_totalRev);
}
}
function addFee(uint _rev) internal {
uint _n = revenueArray.length;
for (uint i = _n - 1; i > 0; i--) {
revenueArray[i] = revenueArray[i - 1];
}
revenueArray[0] = _rev;
}
} | 3,059 | 313 | 1 | 1. [H-01] SynthVault withdraw forfeits rewards
The `SynthVault.withdraw` function does not claim the user's rewards. It decreases the user's weight and therefore they are forfeiting their accumulated rewards. The synthReward variable in `_processWithdraw` is also never used - it was probably intended that this variable captures the claimed rewards.
2. [H-06] SynthVault rewards can be gamed
The SynthVault._deposit function adds weight for the user that depends on the spot value of the deposit synth amount in BASE.
3. [M-04] _deposit resetting user rewards can be used to grief them and make them loose rewards via depositForMember (Timestamp dependence)
The function `_deposit` sets `mapMemberSynth_lastTime` to a date. mapMemberSynth_lastTime is also used to calculate rewards earned. depositForMember allows anyone, to "make a donation" for the member and cause that member to lose all their accrued rewards. This can't be used for personal gain, but can be used to bring misery to others.
4. [M-08] SynthVault deposit lockup bypass
The SynthVault.harvestSingle function can be used to mint & deposit synths without using a lockup. An attacker sends BASE tokens to the pool and then calls harvestSingle. The inner iPOOL(_poolOUT).mintSynth(synth, address(this)); call will mint synth tokens to the vault based on the total BASE balance sent to the pool, including the attacker's previous transfer. They are then credited the entire amount to their weight. | 4 |
28_SushiToken.sol | pragma solidity 0.6.12;
import "./ERC20.sol";
import "../interfaces/IMisoToken.sol";
import "../OpenZeppelin/access/AccessControl.sol";
// ---------------------------------------------------------------------
//
// SushiToken with Governance.
//
// From the MISO Token Factory
// Made for Sushi.com
//
// Enjoy. (c) Chef Gonpachi 2021
// <https://github.com/chefgonpachi/MISO/>
//
// ---------------------------------------------------------------------
// SPDX-License-Identifier: GPL-3.0
// ---------------------------------------------------------------------
contract SushiToken is IMisoToken, AccessControl, ERC20 {
/// @notice Miso template id for the token factory.
/// @dev For different token types, this must be incremented.
uint256 public constant override tokenTemplate = 3;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
function initToken(string memory _name, string memory _symbol, address _owner, uint256 _initialSupply) public {
_initERC20(_name, _symbol);
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(MINTER_ROLE, _owner);
_mint(msg.sender, _initialSupply);
}
function init(bytes calldata _data) external override payable {}
function initToken(
bytes calldata _data
) public override {
(string memory _name,
string memory _symbol,
address _owner,
uint256 _initialSupply) = abi.decode(_data, (string, string, address, uint256));
initToken(_name,_symbol,_owner,_initialSupply);
}
/**
* @dev Generates init data for Token Factory
* @param _name - Token name
* @param _symbol - Token symbol
* @param _owner - Contract owner
* @param _initialSupply Amount of tokens minted on creation
*/
function getInitData(
string calldata _name,
string calldata _symbol,
address _owner,
uint256 _initialSupply
)
external
pure
returns (bytes memory _data)
{
return abi.encode(_name, _symbol, _owner, _initialSupply);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "SushiToken: must have minter role to mint");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public sigNonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == sigNonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2;
// ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
if (currentDelegate != delegatee){
uint256 delegatorBalance = balanceOf(delegator);
// balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* @inheritdoc ERC20
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
_moveDelegates(from, _delegates[to], amount);
super._beforeTokenTransfer(from, to, amount);
}
} | 2,538 | 317 | 1 | 1. H-02: SushiToken transfers are broken due to wrong delegates accounting on transfers (Delegatecall)
When minting / transferring / burning tokens, the SushiToken._beforeTokenTransfer function is called and supposed to correctly shift the voting power due to the increase/decrease in tokens for the from and to accounts. However, it does not correctly do that, it tries to shift the votes from the from account, instead of the `_delegates[from]` account. This can lead to transfers reverting. | 1 |
8_NFTXFeeDistributor.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.6.8;
import "./interface/INFTXLPStaking.sol";
import "./interface/INFTXFeeDistributor.sol";
import "./interface/INFTXVaultFactory.sol";
import "./token/IERC20Upgradeable.sol";
import "./util/SafeERC20Upgradeable.sol";
import "./util/SafeMathUpgradeable.sol";
import "./util/PausableUpgradeable.sol";
import "hardhat/console.sol";
contract NFTXFeeDistributor is INFTXFeeDistributor, PausableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
bool public distributionPaused;
address public override nftxVaultFactory;
address public override lpStaking;
address public override treasury;
uint256 public override defaultTreasuryAlloc;
uint256 public override defaultLPAlloc;
mapping(uint256 => uint256) public override allocTotal;
mapping(uint256 => uint256) public override specificTreasuryAlloc;
mapping(uint256 => FeeReceiver[]) feeReceivers;
event AddFeeReceiver(uint256 vaultId, address receiver, uint256 allocPoint);
event FeeReceiverAllocChange(uint256 vaultId, address receiver, uint256 allocPoint);
event RemoveFeeReceiver(uint256 vaultId, address receiver);
function __FeeDistributor__init__(address _lpStaking, address _treasury) public override initializer {
__Pausable_init();
lpStaking = _lpStaking;
treasury = _treasury;
defaultTreasuryAlloc = 0.2 ether;
defaultLPAlloc = 0.5 ether;
}
function rescue(address token) external override onlyOwner {
uint256 balance = IERC20Upgradeable(token).balanceOf(address(this));
IERC20Upgradeable(token).transfer(msg.sender, balance);
}
function distribute(uint256 vaultId) external override {
require(nftxVaultFactory != address(0));
address _vault = INFTXVaultFactory(nftxVaultFactory).vault(vaultId);
uint256 tokenBalance = IERC20Upgradeable(_vault).balanceOf(address(this));
if (tokenBalance <= 10**9) {
return;
}
// Leave some balance for dust since we know we have more than 10**9.
tokenBalance -= 1000;
uint256 _treasuryAlloc = specificTreasuryAlloc[vaultId];
if (_treasuryAlloc == 0) {
_treasuryAlloc = defaultTreasuryAlloc;
}
uint256 _allocTotal = allocTotal[vaultId] + _treasuryAlloc;
uint256 amountToSend = tokenBalance * _treasuryAlloc / _allocTotal;
amountToSend = amountToSend > tokenBalance ? tokenBalance : amountToSend;
IERC20Upgradeable(_vault).safeTransfer(treasury, amountToSend);
if (distributionPaused) {
return;
}
FeeReceiver[] memory _feeReceivers = feeReceivers[vaultId];
for (uint256 i = 0; i < _feeReceivers.length; i++) {
_sendForReceiver(_feeReceivers[i], vaultId, _vault, tokenBalance, _allocTotal);
}
}
function addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) external override onlyOwner {
_addReceiver(_vaultId, _allocPoint, _receiver, _isContract);
}
function initializeVaultReceivers(uint256 _vaultId) external override {
require(msg.sender == nftxVaultFactory, "FeeReceiver: not factory");
_addReceiver(_vaultId, defaultLPAlloc, lpStaking, true);
INFTXLPStaking(lpStaking).addPoolForVault(_vaultId);
}
function changeReceiverAlloc(uint256 _vaultId, uint256 _receiverIdx, uint256 _allocPoint) external override onlyOwner {
FeeReceiver storage feeReceiver = feeReceivers[_vaultId][_receiverIdx];
allocTotal[_vaultId] -= feeReceiver.allocPoint;
feeReceiver.allocPoint = _allocPoint;
allocTotal[_vaultId] += _allocPoint;
emit FeeReceiverAllocChange(_vaultId, feeReceiver.receiver, _allocPoint);
}
function changeReceiverAddress(uint256 _vaultId, uint256 _receiverIdx, address _address, bool _isContract) external override onlyOwner {
FeeReceiver storage feeReceiver = feeReceivers[_vaultId][_receiverIdx];
feeReceiver.receiver = _address;
feeReceiver.isContract = _isContract;
}
function removeReceiver(uint256 _vaultId, uint256 _receiverIdx) external override onlyOwner {
FeeReceiver[] storage feeReceiversForVault = feeReceivers[_vaultId];
uint256 arrLength = feeReceiversForVault.length;
require(_receiverIdx < arrLength, "FeeDistributor: Out of bounds");
emit RemoveFeeReceiver(_vaultId, feeReceiversForVault[_receiverIdx].receiver);
allocTotal[_vaultId] -= feeReceiversForVault[_receiverIdx].allocPoint;
feeReceiversForVault[_receiverIdx] = feeReceiversForVault[arrLength-1];
feeReceiversForVault.pop();
}
function setTreasuryAddress(address _treasury) external override onlyOwner {
treasury = _treasury;
}
function setDefaultTreasuryAlloc(uint256 _allocPoint) external override onlyOwner {
defaultTreasuryAlloc = _allocPoint;
}
function setSpecificTreasuryAlloc(uint256 vaultId, uint256 _allocPoint) external override onlyOwner {
specificTreasuryAlloc[vaultId] = _allocPoint;
}
function setLPStakingAddress(address _lpStaking) external override onlyOwner {
lpStaking = _lpStaking;
}
function setNFTXVaultFactory(address _factory) external override onlyOwner {
nftxVaultFactory = _factory;
}
function setDefaultLPAlloc(uint256 _allocPoint) external override onlyOwner {
defaultLPAlloc = _allocPoint;
}
function pauseFeeDistribution(bool pause) external onlyOwner {
distributionPaused = pause;
}
function rescueTokens(uint256 _address) external override onlyOwner {
uint256 balance = IERC20Upgradeable(_address).balanceOf(address(this));
IERC20Upgradeable(_address).transfer(msg.sender, balance);
}
function _addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) internal {
allocTotal[_vaultId] += _allocPoint;
FeeReceiver memory _feeReceiver = FeeReceiver(_allocPoint, _receiver, _isContract);
feeReceivers[_vaultId].push(_feeReceiver);
emit AddFeeReceiver(_vaultId, _receiver, _allocPoint);
}
function _sendForReceiver(FeeReceiver memory _receiver, uint256 _vaultId, address _vault, uint256 _tokenBalance, uint256 _allocTotal) internal {
uint256 amountToSend = _tokenBalance * _receiver.allocPoint / _allocTotal;
// If we're at this point we know we have more than enough to perform this safely.
uint256 balance = IERC20Upgradeable(_vault).balanceOf(address(this)) - 1000;
amountToSend = amountToSend > balance ? balance : amountToSend;
if (_receiver.isContract) {
IERC20Upgradeable(_vault).approve(_receiver.receiver, amountToSend);
// If the receive is not properly processed, send it to the treasury instead.
bytes memory payload = abi.encodeWithSelector(INFTXLPStaking.receiveRewards.selector, _vaultId, amountToSend);
(bool success, bytes memory returnData) = address(_receiver.receiver).call(payload);
bool tokensReceived = abi.decode(returnData, (bool));
if (!success || !tokensReceived) {
console.log("treasury fallback");
IERC20Upgradeable(_vault).safeTransfer(treasury, amountToSend);
}
} else {
IERC20Upgradeable(_vault).safeTransfer(_receiver.receiver, amountToSend);
}
}
} | 1,766 | 173 | 3 | 1. [M-05] Unbounded iteration in NFTXEligiblityManager.distribute over _feeReceivers (Gas Limit)
NFTXEligiblityManager.`distribute` iterates over all _feeReceivers. If the number of _feeReceivers gets too big, the transaction's gas cost could exceed the block gas limit and make it impossible to call distribute at all.
2. M-03: Reentrancy
The `distribute` function of `NFTXFeeDistributor` has no access control and will invoke a fallback on the fee receivers, meaning that a fee receiver can re-enter via this function to acquire their allocation repeatedly potentially draining the full balance and sending zero amounts to the rest of the recipients.
3. [M-08] A malicious receiver can cause another receiver to lose out on distributed fees by returning false for tokensReceived when receiveRewards is called on their receiver contract. (Unchecked return calls)
Function `_sendForReceiver()`. A malicious receiver can cause another receiver to lose out on distributed fees by returning false for `tokensReceived` when `receiveRewards` is called on their receiver contract. This causes the fee distributor to double spend the `amountToSend` because the contract incorrectly assumes the returned data is truthful. | 3 |
29_IndexPool.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.0;
import "../interfaces/IBentoBoxMinimal.sol";
import "../interfaces/IMasterDeployer.sol";
import "../interfaces/IPool.sol";
import "../interfaces/ITridentCallee.sol";
import "./TridentERC20.sol";
/// @notice Trident exchange pool template with constant mean formula for swapping among an array of ERC-20 tokens.
/// @dev The reserves are stored as bento shares.
/// The curve is applied to shares as well. This pool does not care about the underlying amounts.
contract IndexPool is IPool, TridentERC20 {
event Mint(address indexed sender, address tokenIn, uint256 amountIn, address indexed recipient);
event Burn(address indexed sender, address tokenOut, uint256 amountOut, address indexed recipient);
uint256 public immutable swapFee;
address public immutable barFeeTo;
address public immutable bento;
address public immutable masterDeployer;
uint256 internal constant BASE = 10**18;
uint256 internal constant MIN_TOKENS = 2;
uint256 internal constant MAX_TOKENS = 8;
uint256 internal constant MIN_FEE = BASE / 10**6;
uint256 internal constant MAX_FEE = BASE / 10;
uint256 internal constant MIN_WEIGHT = BASE;
uint256 internal constant MAX_WEIGHT = BASE * 50;
uint256 internal constant MAX_TOTAL_WEIGHT = BASE * 50;
uint256 internal constant MIN_BALANCE = BASE / 10**12;
uint256 internal constant INIT_POOL_SUPPLY = BASE * 100;
uint256 internal constant MIN_POW_BASE = 1;
uint256 internal constant MAX_POW_BASE = (2 * BASE) - 1;
uint256 internal constant POW_PRECISION = BASE / 10**10;
uint256 internal constant MAX_IN_RATIO = BASE / 2;
uint256 internal constant MAX_OUT_RATIO = (BASE / 3) + 1;
uint136 internal totalWeight;
address[] internal tokens;
uint256 public barFee;
bytes32 public constant override poolIdentifier = "Trident:Index";
uint256 internal unlocked;
modifier lock() {
require(unlocked == 1, "LOCKED");
unlocked = 2;
_;
unlocked = 1;
}
mapping(address => Record) public records;
struct Record {
uint120 reserve;
uint136 weight;
}
constructor(bytes memory _deployData, address _masterDeployer) {
(address[] memory _tokens, uint136[] memory _weights, uint256 _swapFee) = abi.decode(
_deployData,
(address[], uint136[], uint256)
);
// @dev Factory ensures that the tokens are sorted.
require(_tokens.length == _weights.length, "INVALID_ARRAYS");
require(MIN_FEE <= _swapFee && _swapFee <= MAX_FEE, "INVALID_SWAP_FEE");
require(MIN_TOKENS <= _tokens.length && _tokens.length <= MAX_TOKENS, "INVALID_TOKENS_LENGTH");
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != address(0), "ZERO_ADDRESS");
require(MIN_WEIGHT <= _weights[i] && _weights[i] <= MAX_WEIGHT, "INVALID_WEIGHT");
records[_tokens[i]] = Record({reserve: 0, weight: _weights[i]});
tokens.push(_tokens[i]);
totalWeight += _weights[i];
}
require(totalWeight <= MAX_TOTAL_WEIGHT, "MAX_TOTAL_WEIGHT");
// @dev This burns initial LP supply.
_mint(address(0), INIT_POOL_SUPPLY);
(, bytes memory _barFee) = _masterDeployer.staticcall(abi.encodeWithSelector(IMasterDeployer.barFee.selector));
(, bytes memory _barFeeTo) = _masterDeployer.staticcall(abi.encodeWithSelector(IMasterDeployer.barFeeTo.selector));
(, bytes memory _bento) = _masterDeployer.staticcall(abi.encodeWithSelector(IMasterDeployer.bento.selector));
swapFee = _swapFee;
barFee = abi.decode(_barFee, (uint256));
barFeeTo = abi.decode(_barFeeTo, (address));
bento = abi.decode(_bento, (address));
masterDeployer = _masterDeployer;
unlocked = 1;
}
/// @dev Mints LP tokens - should be called via the router after transferring `bento` tokens.
/// The router must ensure that sufficient LP tokens are minted by using the return value.
function mint(bytes calldata data) public override lock returns (uint256 liquidity) {
(address recipient, uint256 toMint) = abi.decode(data, (address, uint256));
uint120 ratio = uint120(_div(toMint, totalSupply));
for (uint256 i = 0; i < tokens.length; i++) {
address tokenIn = tokens[i];
uint120 reserve = records[tokenIn].reserve;
// @dev If token balance is '0', initialize with `ratio`.
uint120 amountIn = reserve != 0 ? uint120(_mul(ratio, reserve)) : ratio;
require(amountIn >= MIN_BALANCE, "MIN_BALANCE");
// @dev Check Trident router has sent `amountIn` for skim into pool.
unchecked {
// @dev This is safe from overflow - only logged amounts handled.
require(_balance(tokenIn) >= amountIn + reserve, "NOT_RECEIVED");
records[tokenIn].reserve += amountIn;
}
emit Mint(msg.sender, tokenIn, amountIn, recipient);
}
_mint(recipient, toMint);
liquidity = toMint;
}
/// @dev Burns LP tokens sent to this contract. The router must ensure that the user gets sufficient output tokens.
function burn(bytes calldata data) public override lock returns (IPool.TokenAmount[] memory withdrawnAmounts) {
(address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(data, (address, bool, uint256));
uint256 ratio = _div(toBurn, totalSupply);
withdrawnAmounts = new TokenAmount[](tokens.length);
_burn(address(this), toBurn);
for (uint256 i = 0; i < tokens.length; i++) {
address tokenOut = tokens[i];
uint256 balance = records[tokenOut].reserve;
uint120 amountOut = uint120(_mul(ratio, balance));
require(amountOut != 0, "ZERO_OUT");
// @dev This is safe from underflow - only logged amounts handled.
unchecked {
records[tokenOut].reserve -= amountOut;
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
withdrawnAmounts[i] = TokenAmount({token: tokenOut, amount: amountOut});
emit Burn(msg.sender, tokenOut, amountOut, recipient);
}
}
/// @dev Burns LP tokens sent to this contract and swaps one of the output tokens for another
/// - i.e., the user gets a single token out by burning LP tokens.
function burnSingle(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenOut, address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(
data,
(address, address, bool, uint256)
);
Record storage outRecord = records[tokenOut];
amountOut = _computeSingleOutGivenPoolIn(
outRecord.reserve,
outRecord.weight,
totalSupply,
totalWeight,
toBurn,
swapFee
);
require(amountOut <= _mul(outRecord.reserve, MAX_OUT_RATIO), "MAX_OUT_RATIO");
// @dev This is safe from underflow - only logged amounts handled.
unchecked {
outRecord.reserve -= uint120(amountOut);
}
_burn(address(this), toBurn);
_transfer(tokenOut, amountOut, recipient, unwrapBento);
emit Burn(msg.sender, tokenOut, amountOut, recipient);
}
/// @dev Swaps one token for another. The router must prefund this contract and ensure there isn't too much slippage.
function swap(bytes calldata data) public override lock returns (uint256 amountOut) {
(address tokenIn, address tokenOut, address recipient, bool unwrapBento, uint256 amountIn) = abi.decode(
data,
(address, address, address, bool, uint256)
);
Record storage inRecord = records[tokenIn];
Record storage outRecord = records[tokenOut];
require(amountIn <= _mul(inRecord.reserve, MAX_IN_RATIO), "MAX_IN_RATIO");
amountOut = _getAmountOut(amountIn, inRecord.reserve, inRecord.weight, outRecord.reserve, outRecord.weight);
// @dev Check Trident router has sent `amountIn` for skim into pool.
unchecked {
// @dev This is safe from under/overflow - only logged amounts handled.
require(_balance(tokenIn) >= amountIn + inRecord.reserve, "NOT_RECEIVED");
inRecord.reserve += uint120(amountIn);
outRecord.reserve -= uint120(amountOut);
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut);
}
/// @dev Swaps one token for another. The router must support swap callbacks and ensure there isn't too much slippage.
function flashSwap(bytes calldata data) public override lock returns (uint256 amountOut) {
(
address tokenIn,
address tokenOut,
address recipient,
bool unwrapBento,
uint256 amountIn,
bytes memory context
) = abi.decode(data, (address, address, address, bool, uint256, bytes));
Record storage inRecord = records[tokenIn];
Record storage outRecord = records[tokenOut];
require(amountIn <= _mul(inRecord.reserve, MAX_IN_RATIO), "MAX_IN_RATIO");
amountOut = _getAmountOut(amountIn, inRecord.reserve, inRecord.weight, outRecord.reserve, outRecord.weight);
ITridentCallee(msg.sender).tridentSwapCallback(context);
// @dev Check Trident router has sent `amountIn` for skim into pool.
unchecked {
// @dev This is safe from under/overflow - only logged amounts handled.
require(_balance(tokenIn) >= amountIn + inRecord.reserve, "NOT_RECEIVED");
inRecord.reserve += uint120(amountIn);
outRecord.reserve -= uint120(amountOut);
}
_transfer(tokenOut, amountOut, recipient, unwrapBento);
emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut);
}
/// @dev Updates `barFee` for Trident protocol.
function updateBarFee() public {
(, bytes memory _barFee) = masterDeployer.staticcall(abi.encodeWithSelector(IMasterDeployer.barFee.selector));
barFee = abi.decode(_barFee, (uint256));
}
function _balance(address token) internal view returns (uint256 balance) {
(, bytes memory data) = bento.staticcall(abi.encodeWithSelector(IBentoBoxMinimal.balanceOf.selector,
token, address(this)));
balance = abi.decode(data, (uint256));
}
function _getAmountOut(
uint256 tokenInAmount,
uint256 tokenInBalance,
uint256 tokenInWeight,
uint256 tokenOutBalance,
uint256 tokenOutWeight
) internal view returns (uint256 amountOut) {
uint256 weightRatio = _div(tokenInWeight, tokenOutWeight);
// @dev This is safe from under/overflow - only logged amounts handled.
unchecked {
uint256 adjustedIn = _mul(tokenInAmount, (BASE - swapFee));
uint256 a = _div(tokenInBalance, tokenInBalance + adjustedIn);
uint256 b = _compute(a, weightRatio);
uint256 c = BASE - b;
amountOut = _mul(tokenOutBalance, c);
}
}
function _compute(uint256 base, uint256 exp) internal pure returns (uint256 output) {
require(MIN_POW_BASE <= base && base <= MAX_POW_BASE, "INVALID_BASE");
uint256 whole = (exp / BASE) * BASE;
uint256 remain = exp - whole;
uint256 wholePow = _pow(base, whole / BASE);
if (remain == 0) output = wholePow;
uint256 partialResult = _powApprox(base, remain, POW_PRECISION);
output = _mul(wholePow, partialResult);
}
function _computeSingleOutGivenPoolIn(
uint256 tokenOutBalance,
uint256 tokenOutWeight,
uint256 _totalSupply,
uint256 _totalWeight,
uint256 toBurn,
uint256 _swapFee
) internal pure returns (uint256 amountOut) {
uint256 normalizedWeight = _div(tokenOutWeight, _totalWeight);
uint256 newPoolSupply = _totalSupply - toBurn;
uint256 poolRatio = _div(newPoolSupply, _totalSupply);
uint256 tokenOutRatio = _pow(poolRatio, _div(BASE, normalizedWeight));
uint256 newBalanceOut = _mul(tokenOutRatio, tokenOutBalance);
uint256 tokenAmountOutBeforeSwapFee = tokenOutBalance - newBalanceOut;
uint256 zaz = (BASE - normalizedWeight) * _swapFee;
amountOut = _mul(tokenAmountOutBeforeSwapFee, (BASE - zaz));
}
function _pow(uint256 a, uint256 n) internal pure returns (uint256 output) {
output = n % 2 != 0 ? a : BASE;
for (n /= 2; n != 0; n /= 2)
a = a * a;
if (n % 2 != 0) output = output * a;
}
function _powApprox(uint256 base, uint256 exp, uint256 precision) internal pure returns (uint256 sum) {
uint256 a = exp;
(uint256 x, bool xneg) = _subFlag(base, BASE);
uint256 term = BASE;
sum = term;
bool negative;
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BASE;
(uint256 c, bool cneg) = _subFlag(a, (bigK - BASE));
term = _mul(term, _mul(c, x));
term = _div(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = sum - term;
} else {
sum = sum + term;
}
}
}
function _subFlag(uint256 a, uint256 b) internal pure returns (uint256 difference, bool flag) {
// @dev This is safe from underflow - if/else flow performs checks.
unchecked {
if (a >= b) {
(difference, flag) = (a - b, false);
} else {
(difference, flag) = (b - a, true);
}
}
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256 c2) {
uint256 c0 = a * b;
uint256 c1 = c0 + (BASE / 2);
c2 = c1 / BASE;
}
function _div(uint256 a, uint256 b) internal pure returns (uint256 c2) {
uint256 c0 = a * BASE;
uint256 c1 = c0 + (b / 2);
c2 = c1 / b;
}
function _transfer(
address token,
uint256 shares,
address to,
bool unwrapBento
) internal {
if (unwrapBento) {
(bool success, ) = bento.call(abi.encodeWithSelector(IBentoBoxMinimal.withdraw.selector,
token, address(this), to, 0, shares));
require(success, "WITHDRAW_FAILED");
} else {
(bool success, ) = bento.call(abi.encodeWithSelector(IBentoBoxMinimal.transfer.selector,
token, address(this), to, shares));
require(success, "TRANSFER_FAILED");
}
}
function getAssets() public view override returns (address[] memory assets) {
assets = tokens;
}
function getAmountOut(bytes calldata data) public view override returns (uint256 amountOut) {
(
uint256 tokenInAmount,
uint256 tokenInBalance,
uint256 tokenInWeight,
uint256 tokenOutBalance,
uint256 tokenOutWeight
) = abi.decode(data, (uint256, uint256, uint256, uint256, uint256));
amountOut = _getAmountOut(tokenInAmount, tokenInBalance, tokenInWeight, tokenOutBalance, tokenOutWeight);
}
function getReservesAndWeights() public view returns (uint256[] memory reserves, uint136[] memory weights) {
uint256 length = tokens.length;
reserves = new uint256[](length);
weights = new uint136[](length);
// @dev This is safe from overflow - `tokens` `length` is bound to '8'.
unchecked {
for (uint256 i = 0; i < length; i++) {
reserves[i] = records[tokens[i]].reserve;
weights[i] = records[tokens[i]].weight;
}
}
}
} | 3,822 | 387 | 2 | 1. [H-01] Flash swap call back prior to transferring tokens in indexPool
IndexPool.sol#L196-L223
In the IndexPool contract, `flashSwap` does not work. The callback function is called prior to token transfer. The sender won't receive tokens in the callBack function. ITridentCallee(msg.sender).tridentSwapCallback(context);
2. [H-02] Index Pool always swap to Zero
IndexPool.sol#L286-L291 in function `_pow`
When an Index pool is initiated with two tokens A: B and the weight rate = 1:2, then no user can buy token A with token B.
3. H-03: IndexPool pow overflows when weightRatio > 10. (Overflow)
In the IndexPool contract, pow is used in calculating price. (IndexPool.sol L255-L266). However, Pow is easy to cause overflow. If the weightRatio is large (e.g. 10), there's always overflow. in `_compute`
4. H-04: IndexPool's INIT_POOL_SUPPLY is not fair.
The `indexPool` mint `INIT_POOL_SUPPLY` to address 0 in the constructor. However, the value of the burned lp is decided by the first lp provider. According to the formula in IndexPool.sol L106.
5. H-06: IndexPool: Poor conversion from Balancer V1's corresponding functions
6. H-07: IndexPool.mint The first liquidity provider is forced to supply assets in the same amount, which may cause a significant amount of fund loss
7. H-09: Unsafe cast in IndexPool mint leads to attack
8. H-10: IndexPool initial LP supply computation is wrong
9. H-13: Overflow in the mint function of IndexPool causes LPs' funds to be stolen L110 (overflow)
10. H-14: Incorrect usage of _pow in _computeSingleOutGivenPoolIn of IndexPool
11. H-15: Incorrect multiplication in _computeSingleOutGivenPoolIn of IndexPool. L282 | 11 |
16_Trader.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./Interfaces/ITracerPerpetualSwaps.sol";
import "./Interfaces/Types.sol";
import "./Interfaces/ITrader.sol";
import "./lib/LibPerpetuals.sol";
import "./lib/LibBalances.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* The Trader contract is used to validate and execute off chain signed and matched orders
*/
contract Trader is ITrader {
// EIP712 Constants
// https://eips.ethereum.org/EIPS/eip-712
string private constant EIP712_DOMAIN_NAME = "Tracer Protocol";
string private constant EIP712_DOMAIN_VERSION = "1.0";
bytes32 private constant EIP712_DOMAIN_SEPERATOR =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// EIP712 Types
bytes32 private constant ORDER_TYPE =
keccak256(
"Order(address maker,address market,uint256 price,uint256 amount,uint256 side,uint256 expires,uint256 created)"
);
uint256 public constant override chainId = 1337;
bytes32 public immutable override EIP712_DOMAIN;
// order hash to memory
mapping(bytes32 => Perpetuals.Order) public orders;
// maps an order hash to its signed order if seen before
mapping(bytes32 => Types.SignedLimitOrder) public orderToSig;
// order hash to amount filled
mapping(bytes32 => uint256) public override filled;
// order hash to average execution price thus far
mapping(bytes32 => uint256) public override averageExecutionPrice;
constructor() {
// Construct the EIP712 Domain
EIP712_DOMAIN = keccak256(
abi.encode(
EIP712_DOMAIN_SEPERATOR,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
chainId,
address(this)
)
);
}
function filledAmount(Perpetuals.Order memory order) external view override returns (uint256) {
return filled[Perpetuals.orderId(order)];
}
function getAverageExecutionPrice(Perpetuals.Order memory order) external view override returns (uint256) {
return averageExecutionPrice[Perpetuals.orderId(order)];
}
/**
* @notice Batch executes maker and taker orders against a given market. Currently matching works
* by matching orders 1 to 1
* @param makers An array of signed make orders
* @param takers An array of signed take orders
*/
function executeTrade(Types.SignedLimitOrder[] memory makers, Types.SignedLimitOrder[] memory takers)
external
override
{
require(makers.length == takers.length, "TDR: Lengths differ");
// safe as we've already bounds checked the array lengths
uint256 n = makers.length;
require(n > 0, "TDR: Received empty arrays");
for (uint256 i = 0; i < n; i++) {
// verify each order individually and together
if (
!isValidSignature(makers[i].order.maker, makers[i]) ||
!isValidSignature(takers[i].order.maker, takers[i]) ||
!isValidPair(takers[i], makers[i])
) {
// skip if either order is invalid
continue;
}
// retrieve orders
// if the order does not exist, it is created here
Perpetuals.Order memory makeOrder = grabOrder(makers, i);
Perpetuals.Order memory takeOrder = grabOrder(takers, i);
bytes32 makerOrderId = Perpetuals.orderId(makeOrder);
bytes32 takerOrderId = Perpetuals.orderId(takeOrder);
uint256 makeOrderFilled = filled[makerOrderId];
uint256 takeOrderFilled = filled[takerOrderId];
uint256 fillAmount = Balances.fillAmount(makeOrder, makeOrderFilled, takeOrder, takeOrderFilled);
uint256 executionPrice = Perpetuals.getExecutionPrice(makeOrder, takeOrder);
uint256 newMakeAverage = Perpetuals.calculateAverageExecutionPrice(
makeOrderFilled,
averageExecutionPrice[makerOrderId],
fillAmount,
executionPrice
);
uint256 newTakeAverage = Perpetuals.calculateAverageExecutionPrice(
takeOrderFilled,
averageExecutionPrice[takerOrderId],
fillAmount,
executionPrice
);
// match orders
// referencing makeOrder.market is safe due to above require
// make low level call to catch revert
// todo this could be succeptible to re-entrancy as
// market is never verified
(bool success, ) = makeOrder.market.call(
abi.encodePacked(
ITracerPerpetualSwaps(makeOrder.market).matchOrders.selector,
abi.encode(makeOrder, takeOrder, fillAmount)
)
);
// ignore orders that cannot be executed
if (!success) continue;
// update order state
filled[makerOrderId] = makeOrderFilled + fillAmount;
filled[takerOrderId] = takeOrderFilled + fillAmount;
averageExecutionPrice[makerOrderId] = newMakeAverage;
averageExecutionPrice[takerOrderId] = newTakeAverage;
}
}
/**
* @notice Retrieves and validates an order from an order array
* @param signedOrders an array of signed orders
* @param index the index into the array where the desired order is
* @return the specified order
* @dev Should only be called with a verified signedOrder and with index
* < signedOrders.length
*/
function grabOrder(Types.SignedLimitOrder[] memory signedOrders, uint256 index)
internal
returns (Perpetuals.Order memory)
{
Perpetuals.Order memory rawOrder = signedOrders[index].order;
bytes32 orderHash = Perpetuals.orderId(rawOrder);
// check if order exists on chain, if not, create it
if (orders[orderHash].maker == address(0)) {
// store this order to keep track of state
orders[orderHash] = rawOrder;
// map the order hash to the signed order
orderToSig[orderHash] = signedOrders[index];
}
return orders[orderHash];
}
/**
* @notice hashes a limit order type in order to verify signatures, per EIP712
* @param order the limit order being hashed
* @return an EIP712 compliant hash (with headers) of the limit order
*/
function hashOrder(Perpetuals.Order memory order) public view override returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19\x01",
EIP712_DOMAIN,
keccak256(
abi.encode(
ORDER_TYPE,
order.maker,
order.market,
order.price,
order.amount,
uint256(order.side),
order.expires,
order.created
)
)
)
);
}
/**
* @notice Gets the EIP712 domain hash of the contract
*/
function getDomain() external view override returns (bytes32) {
return EIP712_DOMAIN;
}
/**
* @notice Verifies a given limit order has been signed by a given signer and has a correct nonce
* @param signer The signer who is being verified against the order
* @param signedOrder The signed order to verify the signature of
* @return if an order has a valid signature and a valid nonce
* @dev does not throw if the signature is invalid.
*/
function isValidSignature(address signer, Types.SignedLimitOrder memory signedOrder) internal view returns (bool) {
return verifySignature(signer, signedOrder);
}
/**
* @notice Validates a given pair of signed orders against each other
* @param signedOrder1 the first signed order
* @param signedOrder2 the second signed order
* @return if signedOrder1 is compatible with signedOrder2
* @dev does not throw if pairs are invalid
*/
function isValidPair(Types.SignedLimitOrder memory signedOrder1, Types.SignedLimitOrder memory signedOrder2)
internal
pure
returns (bool)
{
return (signedOrder1.order.market == signedOrder2.order.market);
}
/**
* @notice Verifies the signature component of a signed order
* @param signer The signer who is being verified against the order
* @param signedOrder The unsigned order to verify the signature of
* @return true is signer has signed the order, else false
*/
function verifySignature(address signer, Types.SignedLimitOrder memory signedOrder)
public
view
override
returns (bool)
{
return
signer == ECDSA.recover(hashOrder(signedOrder.order), signedOrder.sigV, signedOrder.sigR, signedOrder.sigS);
}
/**
* @return An order that has been previously created in contract, given a user-supplied order
* @dev Useful for checking to see if a supplied order has actually been created
*/
function getOrder(Perpetuals.Order calldata order) external view override returns (Perpetuals.Order memory) {
bytes32 orderId = Perpetuals.orderId(order);
return orders[orderId];
}
} | 2,063 | 250 | 2 | 1. [M-05] Add reentrancy protections on function executeTrade (reentrancy)
As written in the to-do comments, reentrancy could happen in the `executeTrade` function of Trader since the makeOrder.market can be a user-controlled external contract.
2. [M-13] Trader orders can be front-run and users can be denied from trading (front-running)
The Trader contract accepts two signed orders and tries to match them. Once they are matched and become filled, they can therefore not be matched against other orders anymore. | 2 |
78_FlashGovernanceArbiter.sol | // SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./Governable.sol";
import "hardhat/console.sol";
import "../facades/Burnable.sol";
///@title Flash Governance Arbiter
///@author Justin Goro
/**@notice LimboDAO offers two forms of governance: flash and proposal. Proposals are contracts that have authorization to execute guarded functions on contracts that implement the Governable abstract contract.
* Proposals require Fate to be put forward for voting and Fate is the spendable voting token.
* Flash governance occurs in the duration of one transaction and is more appropriate for variable tweaking such as changing the Flan per Second or Threshold of a pool.
* Flash governance requires an asset be deposited into an adjudication contract. The community can then vote, through a proposal, whether the decision was legitimate. If not, the deposit can be slashed
* By default, the asset is EYE.
*/
contract FlashGovernanceArbiter is Governable {
/**
* @param actor user making flash governance decision
* @param deposit_asset is the asset type put up as decision collateral. Must be burnable.
* @param amount is the amount of the deposit_asset to be put up as decision collateral.
* @param target is the contract that will be affected by the flash governance decision.
*/
event flashDecision(address actor, address deposit_asset, uint256 amount, address target);
mapping(address => bool) enforceLimitsActive;
constructor(address dao) Governable(dao) {}
struct FlashGovernanceConfig {
address asset;
uint256 amount;
uint256 unlockTime;
bool assetBurnable;
}
//Note: epoch settings prevent DOS attacks. Change tolerance curtails the damage of bad flash governance.
struct SecurityParameters {
uint8 maxGovernanceChangePerEpoch;
//prevents flash governance from wrecking the incentives.
uint256 epochSize;
//only one flash governance action can happen per epoch to prevent governance DOS
uint256 lastFlashGovernanceAct;
uint8 changeTolerance;
//1-100 maximum percentage any numeric variable can be changed through flash gov
}
//the current parameters determining the rules of flash governance
FlashGovernanceConfig public flashGovernanceConfig;
SecurityParameters public security;
/*For every decision, we record the config at the time of the decision. This allows governance to change the rules
*without undermining the terms under which pending decisions were made.
*/
mapping(address => mapping(address => FlashGovernanceConfig)) public pendingFlashDecision;
//contract->user->config
/**
*@notice An attempt is made to withdraw the current deposit requirement.
* For a given user, flash governance decisions can only happen one at a time
*@param sender is the user making the flash governance decision
*@param target is the contract that will be affected by the flash governance decision.
*@param emergency flash governance decisions are restricted in frequency per epoch but some decisions are too important. These can be marked emergency.
*@dev be very careful about setting emergency to true. Only decisions which preclude the execution of other flash governance decisions should be considered candidtes for emergency.
*/
function assertGovernanceApproved(
address sender,
address target,
bool emergency
) public {
if (
IERC20(flashGovernanceConfig.asset).transferFrom(sender, address(this), flashGovernanceConfig.amount) &&
pendingFlashDecision[target][sender].unlockTime < block.timestamp
) {
require(
emergency || (block.timestamp - security.lastFlashGovernanceAct > security.epochSize),
"Limbo: flash governance disabled for rest of epoch"
);
pendingFlashDecision[target][sender] = flashGovernanceConfig;
pendingFlashDecision[target][sender].unlockTime += block.timestamp;
security.lastFlashGovernanceAct = block.timestamp;
emit flashDecision(sender, flashGovernanceConfig.asset, flashGovernanceConfig.amount, target);
} else {
revert("LIMBO: governance decision rejected.");
}
}
/**
*@param asset is the asset type put up as decision collateral. Must be burnable.
*@param amount is the amount of the deposit_asset to be put up as decision collateral.
*@param unlockTime is the duration for which the deposit collateral must be locked in order to give the community time to weigh up the decision
*@param assetBurnable is a technical parameter to determined the manner in which burning should occur. Non burnable assets are just no longer accounted for and accumulate within this contract.
*/
function configureFlashGovernance(
address asset,
uint256 amount,
uint256 unlockTime,
bool assetBurnable
) public virtual onlySuccessfulProposal {
flashGovernanceConfig.asset = asset;
flashGovernanceConfig.amount = amount;
flashGovernanceConfig.unlockTime = unlockTime;
flashGovernanceConfig.assetBurnable = assetBurnable;
}
/**
@param maxGovernanceChangePerEpoch max number of flash governance decisions per epoch to prevent DOS
@param epochSize is the duration of a flash governance epoch and reflects proposal deliberation durations
@param changeTolerance is the amount by which a variable can be changed through flash governance.
*/
function configureSecurityParameters(
uint8 maxGovernanceChangePerEpoch,
uint256 epochSize,
uint8 changeTolerance
) public virtual onlySuccessfulProposal {
security.maxGovernanceChangePerEpoch = maxGovernanceChangePerEpoch;
security.epochSize = epochSize;
require(security.changeTolerance < 100, "Limbo: % between 0 and 100");
security.changeTolerance = changeTolerance;
}
/**
@notice LimboDAO proposals for burning flash governance collateral act through this function
@param targetContract is the contract that is affected by the flash governance decision.
@param user is the user who made the flash governance decision
@param asset is the collateral asset to be burnt
@param amount is the amount of the collateral to be burnt
*/
function burnFlashGovernanceAsset(
address targetContract,
address user,
address asset,
uint256 amount
) public virtual onlySuccessfulProposal {
if (pendingFlashDecision[targetContract][user].assetBurnable) {
Burnable(asset).burn(amount);
}
pendingFlashDecision[targetContract][user] = flashGovernanceConfig;
}
/**
*@notice Assuming a flash governance decision was not rejected during the lock window, the user is free to withdraw their asset
*@param targetContract is the contract that is affected by the flash governance decision.
*@param asset is the collateral asset to be withdrawn
*/
function withdrawGovernanceAsset(address targetContract, address asset) public virtual {
require(
pendingFlashDecision[targetContract][msg.sender].asset == asset &&
pendingFlashDecision[targetContract][msg.sender].amount > 0 &&
pendingFlashDecision[targetContract][msg.sender].unlockTime < block.timestamp,
"Limbo: Flashgovernance decision pending."
);
IERC20(pendingFlashDecision[targetContract][msg.sender].asset).transfer(
msg.sender,
pendingFlashDecision[targetContract][msg.sender].amount
);
delete pendingFlashDecision[targetContract][msg.sender];
}
/**
*@notice when a governance function is executed, it can enforce change limits on variables in the event that the execution is through flash governance
* However, a proposal is subject to the full deliberation of the DAO and such limits may thwart good governance.
* @param enforce for the given context, set whether variable movement limits are enforced or not.
*/
function setEnforcement(bool enforce) public {
enforceLimitsActive[msg.sender] = enforce;
}
///@dev for negative values, relative comparisons need to be calculated correctly.
function enforceToleranceInt(int256 v1, int256 v2) public view {
if (!configured) return;
uint256 uv1 = uint256(v1 > 0 ? v1 : -1 * v1);
uint256 uv2 = uint256(v2 > 0 ? v2 : -1 * v2);
enforceTolerance(uv1, uv2);
}
///@notice Allows functions to enforce maximum limits on a per variable basis
///@dev the 100 factor is just to allow for simple percentage comparisons without worrying about enormous precision.
function enforceTolerance(uint256 v1, uint256 v2) public view {
if (!configured || !enforceLimitsActive[msg.sender]) return;
//bonus points for readability
if (v1 > v2) {
if (v2 == 0) require(v1 <= 1, "FE1");
else require(((v1 - v2) * 100) < security.changeTolerance * v1, "FE1");
} else {
if (v1 == 0) require(v2 <= 1, "FE1");
else require(((v2 - v1) * 100) < security.changeTolerance * v1, "FE1");
}
}
} | 1,932 | 191 | 3 | 1. H-01: Lack of access control on `assertGovernanceApproved` can cause funds to be locked (Lack of Access Control)
Lack of access control on the `assertGovernanceApproved` function of FlashGovernanceArbiter allows anyone to lock other users' funds in the contract as long as the users have approved the contract to transfer flashGovernanceConfig.amount of flashGovernanceConfig.asset from them.
2. [H-04] Logic error in burnFlashGovernanceAsset can cause locked assets to be stolen
A logic error in the `burnFlashGovernanceAsset` function that resets a user's pendingFlashDecision allows that user to steal other user's assets locked in future flash governance decisions. As a result, attackers can get their funds back even if they execute a malicious flash decision and the community burns their assets.
3. [H-06] Loss Of Flash Governance Tokens If They Are Not Withdrawn Before The Next Request (Flash governance)
Users who have not called `withdrawGovernanceAsset()` after they have locked their tokens from a previous proposal (i.e. `assertGovernanceApproved`), will lose their tokens if assertGovernanceApproved() is called again with the same target and sender.
4. [M-01] Incorrect unlockTime can DOS withdrawGovernanceAsset (Timestamp manipulation)
`withdrawGovernanceAsset()`
5. [M-02] Reentrancy on Flash Governance Proposal Withdrawal (reentrancy)
The function withdrawGovernanceAsset() is vulnerable to reentrancy, which would allow the attacker to drain the balance of the flashGoverananceConfig.asset.
6. [M-03] Burning a User's Tokens for a Flash Proposal will not Deduct Their Balance
The function burnFlashGovernanceAsset() will simply overwrite the user's state with pendingFlashDecision[targetContract][user] = flashGovernanceConfig; as seen below. | 6 |
12_Witch.sol | // SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./utils/access/AccessControl.sol";
import "./interfaces/vault/ILadle.sol";
import "./interfaces/vault/ICauldron.sol";
import "./interfaces/vault/DataTypes.sol";
import "./math/WMul.sol";
import "./math/WDiv.sol";
import "./math/WDivUp.sol";
import "./math/CastU256U128.sol";
contract Witch is AccessControl() {
using WMul for uint256;
using WDiv for uint256;
using WDivUp for uint256;
using CastU256U128 for uint256;
event AuctionTimeSet(uint128 indexed auctionTime);
event InitialProportionSet(uint128 indexed initialProportion);
event Bought(bytes12 indexed vaultId, address indexed buyer, uint256 ink, uint256 art);
uint128 public auctionTime = 4 * 60 * 60;
uint128 public initialProportion = 5e17;
ICauldron immutable public cauldron;
ILadle immutable public ladle;
mapping(bytes12 => address) public vaultOwners;
constructor (ICauldron cauldron_, ILadle ladle_) {
cauldron = cauldron_;
ladle = ladle_;
}
/// @dev Set the auction time to calculate liquidation prices
function setAuctionTime(uint128 auctionTime_) public auth {
auctionTime = auctionTime_;
emit AuctionTimeSet(auctionTime_);
}
/// @dev Set the proportion of the collateral that will be sold at auction start
function setInitialProportion(uint128 initialProportion_) public auth {
require (initialProportion_ <= 1e18, "Only at or under 100%");
initialProportion = initialProportion_;
emit InitialProportionSet(initialProportion_);
}
/// @dev Put an undercollateralized vault up for liquidation.
function grab(bytes12 vaultId) public {
DataTypes.Vault memory vault = cauldron.vaults(vaultId);
vaultOwners[vaultId] = vault.owner;
cauldron.grab(vaultId, address(this));
}
/// @dev Buy an amount of collateral off a vault in liquidation, paying at most `max` underlying.
function buy(bytes12 vaultId, uint128 art, uint128 min) public {
DataTypes.Balances memory balances_ = cauldron.balances(vaultId);
require (balances_.art > 0, "Nothing to buy");
uint256 elapsed = uint32(block.timestamp) - cauldron.auctions(vaultId);
uint256 price;
{
// Price of a collateral unit, in underlying, at the present moment, for a given vault
//
// ink min(auction, elapsed)
// price = 1 / (------- * (p + (1 - p) * -----------------------))
// art auction
(uint256 auctionTime_, uint256 initialProportion_) = (auctionTime, initialProportion);
uint256 term1 = uint256(balances_.ink).wdiv(balances_.art);
uint256 dividend2 = auctionTime_ < elapsed ? auctionTime_ : elapsed;
uint256 divisor2 = auctionTime_;
uint256 term2 = initialProportion_ + (1e18 - initialProportion_).wmul(dividend2.wdiv(divisor2));
price = uint256(1e18).wdiv(term1.wmul(term2));
}
uint256 ink = uint256(art).wdivup(price);
require (ink >= min, "Not enough bought");
ladle.settle(vaultId, msg.sender, ink.u128(), art);
if (balances_.art - art == 0) {
cauldron.give(vaultId, vaultOwners[vaultId]);
delete vaultOwners[vaultId];
}
emit Bought(vaultId, msg.sender, ink, art);
}
} | 867 | 87 | 1 | 1. [M-03] Witch can't give back vault after 2x grab (Reentrancy)
The witch.sol contract gets access to a vault via the grab function in case of liquidation. If the witch.sol contract can't sell the debt within a certain amount of time, a second grab can occur. | 1 |
19_TransactionManager.sol | pragma solidity 0.8.4;
import "./interfaces/IFulfillHelper.sol";
import "./interfaces/ITransactionManager.sol";
import "./lib/LibAsset.sol";
import "./lib/LibERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract TransactionManager is ReentrancyGuard, ITransactionManager {
mapping(address => mapping(address => uint256)) public routerBalances;
mapping(address => uint256[]) public activeTransactionBlocks;
mapping(bytes32 => bytes32) public variantTransactionData;
uint256 public immutable chainId;
uint256 public constant MIN_TIMEOUT = 24 hours;
constructor(uint256 _chainId) {
chainId = _chainId;
}
function addLiquidity(uint256 amount, address assetId, address router) external payable override nonReentrant {
require(amount > 0, "addLiquidity: AMOUNT_IS_ZERO");
if (LibAsset.isEther(assetId)) {
require(msg.value == amount, "addLiquidity: VALUE_MISMATCH");
} else {
require(msg.value == 0, "addLiquidity: ETH_WITH_ERC_TRANSFER");
require(LibERC20.transferFrom(assetId, router, address(this), amount), "addLiquidity: ERC20_TRANSFER_FAILED");
}
routerBalances[router][assetId] += amount;
emit LiquidityAdded(router, assetId, amount, msg.sender);
}
function removeLiquidity(
uint256 amount,
address assetId,
address payable recipient
) external override nonReentrant {
require(amount > 0, "removeLiquidity: AMOUNT_IS_ZERO");
require(routerBalances[msg.sender][assetId] >= amount, "removeLiquidity: INSUFFICIENT_FUNDS");
routerBalances[msg.sender][assetId] -= amount;
require(LibAsset.transferAsset(assetId, recipient, amount), "removeLiquidity: TRANSFER_FAILED");
emit LiquidityRemoved(msg.sender, assetId, amount, recipient);
}
function prepare(
InvariantTransactionData calldata invariantData,
uint256 amount,
uint256 expiry,
bytes calldata encryptedCallData,
bytes calldata encodedBid,
bytes calldata bidSignature
) external payable override nonReentrant returns (TransactionData memory) {
require(invariantData.user != address(0), "prepare: USER_EMPTY");
require(invariantData.router != address(0), "prepare: ROUTER_EMPTY");
require(invariantData.receivingAddress != address(0), "prepare: RECEIVING_ADDRESS_EMPTY");
require(invariantData.sendingChainId != invariantData.receivingChainId, "prepare: SAME_CHAINIDS");
require(invariantData.sendingChainId == chainId || invariantData.receivingChainId == chainId, "prepare: INVALID_CHAINIDS");
require((expiry - block.timestamp) >= MIN_TIMEOUT, "prepare: TIMEOUT_TOO_LOW");
bytes32 digest = keccak256(abi.encode(invariantData));
require(variantTransactionData[digest] == bytes32(0), "prepare: DIGEST_EXISTS");
variantTransactionData[digest] = keccak256(abi.encode(VariantTransactionData({
amount: amount,
expiry: expiry,
preparedBlockNumber: block.number
})));
activeTransactionBlocks[invariantData.user].push(block.number);
if (invariantData.sendingChainId == chainId) {
require(amount > 0, "prepare: AMOUNT_IS_ZERO");
if (LibAsset.isEther(invariantData.sendingAssetId)) {
require(msg.value == amount, "prepare: VALUE_MISMATCH");
} else {
require(msg.value == 0, "prepare: ETH_WITH_ERC_TRANSFER");
require(
LibERC20.transferFrom(invariantData.sendingAssetId, msg.sender, address(this), amount),
"prepare: ERC20_TRANSFER_FAILED"
);
}
} else {
require(msg.sender == invariantData.router, "prepare: ROUTER_MISMATCH");
require(msg.value == 0, "prepare: ETH_WITH_ROUTER_PREPARE");
require(
routerBalances[invariantData.router][invariantData.receivingAssetId] >= amount,
"prepare: INSUFFICIENT_LIQUIDITY"
);
routerBalances[invariantData.router][invariantData.receivingAssetId] -= amount;
}
TransactionData memory txData = TransactionData({
user: invariantData.user,
router: invariantData.router,
sendingAssetId: invariantData.sendingAssetId,
receivingAssetId: invariantData.receivingAssetId,
sendingChainFallback: invariantData.sendingChainFallback,
callTo: invariantData.callTo,
receivingAddress: invariantData.receivingAddress,
callDataHash: invariantData.callDataHash,
transactionId: invariantData.transactionId,
sendingChainId: invariantData.sendingChainId,
receivingChainId: invariantData.receivingChainId,
amount: amount,
expiry: expiry,
preparedBlockNumber: block.number
});
emit TransactionPrepared(txData.user, txData.router, txData.transactionId, txData, msg.sender, encryptedCallData, encodedBid, bidSignature);
return txData;
}
function fulfill(
TransactionData calldata txData,
uint256 relayerFee,
bytes calldata signature,
bytes calldata callData
) external override nonReentrant returns (TransactionData memory) {
bytes32 digest = hashInvariantTransactionData(txData);
require(variantTransactionData[digest] == hashVariantTransactionData(txData), "fulfill: INVALID_VARIANT_DATA");
require(txData.expiry > block.timestamp, "fulfill: EXPIRED");
require(txData.preparedBlockNumber > 0, "fulfill: ALREADY_COMPLETED");
require(recoverFulfillSignature(txData, relayerFee, signature) == txData.user, "fulfill: INVALID_SIGNATURE");
require(relayerFee <= txData.amount, "fulfill: INVALID_RELAYER_FEE");
require(keccak256(callData) == txData.callDataHash, "fulfill: INVALID_CALL_DATA");
variantTransactionData[digest] = keccak256(abi.encode(VariantTransactionData({
amount: txData.amount,
expiry: txData.expiry,
preparedBlockNumber: 0
})));
removeUserActiveBlocks(txData.user, txData.preparedBlockNumber);
if (txData.sendingChainId == chainId) {
require(msg.sender == txData.router, "fulfill: ROUTER_MISMATCH");
routerBalances[txData.router][txData.sendingAssetId] += txData.amount;
} else {
uint256 toSend = txData.amount - relayerFee;
if (relayerFee > 0) {
require(
LibAsset.transferAsset(txData.receivingAssetId, payable(msg.sender), relayerFee),
"fulfill: FEE_TRANSFER_FAILED"
);
}
if (txData.callTo == address(0)) {
require(
LibAsset.transferAsset(txData.receivingAssetId, payable(txData.receivingAddress), toSend),
"fulfill: TRANSFER_FAILED"
);
} else {
if (!LibAsset.isEther(txData.receivingAssetId) && toSend > 0) {
require(LibERC20.approve(txData.receivingAssetId, txData.callTo, toSend), "fulfill: APPROVAL_FAILED");
}
if (toSend > 0) {
try
IFulfillHelper(txData.callTo).addFunds{ value: LibAsset.isEther(txData.receivingAssetId) ? toSend : 0}(
txData.user,
txData.transactionId,
txData.receivingAssetId,
toSend
)
{} catch {
require(
LibAsset.transferAsset(txData.receivingAssetId, payable(txData.receivingAddress), toSend),
"fulfill: TRANSFER_FAILED"
);
}
}
try
IFulfillHelper(txData.callTo).execute(
txData.user,
txData.transactionId,
txData.receivingAssetId,
toSend,
callData
)
{} catch {
require(
LibAsset.transferAsset(txData.receivingAssetId, payable(txData.receivingAddress), toSend),
"fulfill: TRANSFER_FAILED"
);
}
}
}
emit TransactionFulfilled(txData.user, txData.router, txData.transactionId, txData, relayerFee, signature, callData, msg.sender);
return txData;
}
function cancel(TransactionData calldata txData, uint256 relayerFee, bytes calldata signature)
external
override
nonReentrant
returns (TransactionData memory)
{
bytes32 digest = hashInvariantTransactionData(txData);
require(variantTransactionData[digest] == hashVariantTransactionData(txData), "cancel: INVALID_VARIANT_DATA");
require(txData.preparedBlockNumber > 0, "cancel: ALREADY_COMPLETED");
require(relayerFee <= txData.amount, "cancel: INVALID_RELAYER_FEE");
variantTransactionData[digest] = keccak256(abi.encode(VariantTransactionData({
amount: txData.amount,
expiry: txData.expiry,
preparedBlockNumber: 0
})));
removeUserActiveBlocks(txData.user, txData.preparedBlockNumber);
if (txData.sendingChainId == chainId) {
if (txData.expiry >= block.timestamp) {
require(msg.sender == txData.router, "cancel: ROUTER_MUST_CANCEL");
require(
LibAsset.transferAsset(txData.sendingAssetId, payable(txData.sendingChainFallback), txData.amount),
"cancel: TRANSFER_FAILED"
);
} else {
if (relayerFee > 0) {
require(recoverCancelSignature(txData, relayerFee, signature) == txData.user, "cancel: INVALID_SIGNATURE");
require(
LibAsset.transferAsset(txData.receivingAssetId, payable(msg.sender), relayerFee),
"cancel: FEE_TRANSFER_FAILED"
);
}
uint256 toRefund = txData.amount - relayerFee;
if (toRefund > 0) {
require(
LibAsset.transferAsset(txData.sendingAssetId, payable(txData.sendingChainFallback), toRefund),
"cancel: TRANSFER_FAILED"
);
}
}
} else {
if (txData.expiry >= block.timestamp) {
require(recoverCancelSignature(txData, relayerFee, signature) == txData.user, "cancel: INVALID_SIGNATURE");
}
routerBalances[txData.router][txData.receivingAssetId] += txData.amount;
}
emit TransactionCancelled(txData.user, txData.router, txData.transactionId, txData, relayerFee, msg.sender);
return txData;
}
function getActiveTransactionBlocks(address user) external override view returns (uint256[] memory) {
return activeTransactionBlocks[user];
}
function removeUserActiveBlocks(address user, uint256 preparedBlock) internal {
uint256 newLength = activeTransactionBlocks[user].length - 1;
uint256[] memory updated = new uint256[](newLength);
bool removed = false;
uint256 updatedIdx = 0;
for (uint256 i; i < newLength + 1; i++) {
if (!removed && activeTransactionBlocks[user][i] == preparedBlock) {
removed = true;
continue;
}
updated[updatedIdx] = activeTransactionBlocks[user][i];
updatedIdx++;
}
activeTransactionBlocks[user] = updated;
}
function recoverFulfillSignature(
TransactionData calldata txData,
uint256 relayerFee,
bytes calldata signature
) internal pure returns (address) {
SignedFulfillData memory payload = SignedFulfillData({transactionId: txData.transactionId, relayerFee: relayerFee});
return ECDSA.recover(ECDSA.toEthSignedMessageHash(keccak256(abi.encode(payload))), signature);
}
function recoverCancelSignature(TransactionData calldata txData, uint256 relayerFee, bytes calldata signature)
internal
pure
returns (address)
{
SignedCancelData memory payload = SignedCancelData({transactionId: txData.transactionId, cancel: "cancel", relayerFee: relayerFee});
return ECDSA.recover(ECDSA.toEthSignedMessageHash(keccak256(abi.encode(payload))), signature);
}
function hashInvariantTransactionData(TransactionData calldata txData) internal pure returns (bytes32) {
InvariantTransactionData memory invariant = InvariantTransactionData({
user: txData.user,
router: txData.router,
sendingAssetId: txData.sendingAssetId,
receivingAssetId: txData.receivingAssetId,
sendingChainFallback: txData.sendingChainFallback,
callTo: txData.callTo,
receivingAddress: txData.receivingAddress,
sendingChainId: txData.sendingChainId,
receivingChainId: txData.receivingChainId,
callDataHash: txData.callDataHash,
transactionId: txData.transactionId
});
return keccak256(abi.encode(invariant));
}
function hashVariantTransactionData(TransactionData calldata txData) internal pure returns (bytes32) {
return keccak256(abi.encode(VariantTransactionData({
amount: txData.amount,
expiry: txData.expiry,
preparedBlockNumber: txData.preparedBlockNumber
})));
}
} | 2,943 | 278 | 2 | 1. [H-01] Anyone can arbitrarily add router liquidity. L88-L98. (Access control)
The `addLiquidity()` function takes a router address parameter, whose liquidity is increased (instead of assuming that router == msg.sender like is done on removeLiquidity()) on this contract/chain, by transferring the fund amount from router address to this contract if assetID != 0 (i.e. ERC20 tokens). However, anyone can call this function on the router’s behalf. For assetID == 0, the Ether transfer via msg.value comes from msg.sender and hence is assumed to be the router itself.
2. [H-03] Router liquidity on receiving chain can be double-dipped by the user (Reentrancy)
During `fulfill()` on the receiving chain, if the user has set up an external contract at txData.callTo, the catch blocks for both IFulfillHelper.addFunds() and IFulfillHelper.excute() perform transferAsset to the predetermined fallback address txData.receivingAddress.
3. [H-04] Expired transfers will lock user funds on the sending chain. (Fund locked).
The cancelling relayer is being paid in `receivingAssetId` on the `sendingChain` instead of in `sendingAssetID`. | 3 |
23_CompoundToNotionalV2.sol | // SPDX-License-Identifier: GPL-3.0-only
pragma solidity >0.7.0;
pragma experimental ABIEncoderV2;
import "interfaces/compound/CTokenInterface.sol";
import "interfaces/compound/CErc20Interface.sol";
import "interfaces/notional/NotionalProxy.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract CompoundToNotionalV2 {
NotionalProxy public immutable NotionalV2;
address public owner;
constructor(NotionalProxy notionalV2_) {
NotionalV2 = notionalV2_;
owner = msg.sender;
}
function enableToken(address token, address spender) external {
require(msg.sender == owner, "Unauthorized");
CTokenInterface(token).approve(spender, type(uint256).max);
}
function migrateBorrowFromCompound(
address cTokenBorrow,
uint256 cTokenRepayAmount,
uint16[] memory notionalV2CollateralIds,
uint256[] memory notionalV2CollateralAmounts,
BalanceActionWithTrades[] calldata borrowAction
) external {
// borrow on notional via special flash loan facility
// - borrow repayment amount
// - withdraw to wallet, redeem to underlying
// receive callback (tokens transferred to borrowing account)
// -> inside callback
// -> repayBorrowBehalf(account, repayAmount)
// -> deposit cToken to notional (account needs to have set approvals)
// -> exit callback
// inside original borrow, check FC
uint256 borrowBalance = CTokenInterface(cTokenBorrow).borrowBalanceCurrent(msg.sender);
if (cTokenRepayAmount == 0) {
// Set the entire borrow balance if it is not set
cTokenRepayAmount = borrowBalance;
} else {
// Check that the cToken repayment amount is not more than required
require(cTokenRepayAmount <= borrowBalance, "Invalid repayment amount");
}
bytes memory encodedData = abi.encode(
cTokenBorrow,
cTokenRepayAmount,
notionalV2CollateralIds,
notionalV2CollateralAmounts
);
NotionalV2.batchBalanceAndTradeActionWithCallback(msg.sender, borrowAction, encodedData);
}
function notionalCallback(
address sender,
address account,
bytes calldata callbackData
) external returns (uint256) {
require(sender == address(this), "Unauthorized callback");
(
address cTokenBorrow,
uint256 cTokenRepayAmount,
uint16[] memory notionalV2CollateralIds,
uint256[] memory notionalV2CollateralAmounts
) = abi.decode(callbackData, (address, uint256, uint16[], uint256[]));
// Transfer in the underlying amount that was borrowed
address underlyingToken = CTokenInterface(cTokenBorrow).underlying();
bool success = IERC20(underlyingToken).transferFrom(account, address(this), cTokenRepayAmount);
require(success, "Transfer of repayment failed");
// Use the amount transferred to repay the borrow
uint code = CErc20Interface(cTokenBorrow).repayBorrowBehalf(account, cTokenRepayAmount);
require(code == 0, "Repay borrow behalf failed");
for (uint256 i; i < notionalV2CollateralIds.length; i++) {
(Token memory assetToken, /* */) = NotionalV2.getCurrency(notionalV2CollateralIds[i]);
// Transfer the collateral to this contract so we can deposit it
success = CTokenInterface(assetToken.tokenAddress).transferFrom(account, address(this), notionalV2CollateralAmounts[i]);
require(success, "cToken transfer failed");
// Deposit the cToken into the account's portfolio, no free collateral check is triggered here
NotionalV2.depositAssetToken(account, notionalV2CollateralIds[i], notionalV2CollateralAmounts[i]);
}
// When this exits a free collateral check will be triggered
}
receive() external payable {
// This contract cannot migrate ETH loans because there is no way
// to do transferFrom on ETH
revert("Cannot transfer ETH");
}
} | 924 | 99 | 3 | 1. H-03: CompoundToNotionalV2.notionalCallback ERC20 return values not checked (Unchecked external calls)
Some tokens (like USDT) don't correctly implement the EIP20 standard and their `transfer/transferFrom` functions return `void`, instead of a success boolean. Calling these functions with the correct EIP20 function signatures will always revert. See `CompoundToNotionalV2.notionalCallback's IERC20(underlyingToken).transferFrom call.
2. H-04: Access restrictions on CompoundToNotionalV2.notionalCallback can be bypassed (Access control)
The CompoundToNotionalV2.notionalCallback is supposed to only be called from the verified contract that calls this callback. But, the access restrictions can be circumvented by simply providing sender = this, as sender is a parameter of the function that can be chosen by the attacker.
3. M-04: CompoundToNotionalV2.enableToken ERC20 missing return value check (Unchecked external calls)
The enableToken function performs an ERC20.approve() call but does not check the success return value. Some tokens do not revert if the approval failed, returning false instead. | 3 |
8_NFTXVaultUpgradeable.sol | // SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
import "./interface/INFTXVaultFactory.sol";
import "./interface/INFTXEligibility.sol";
import "./interface/INFTXEligibilityManager.sol";
import "./interface/INFTXLPStaking.sol";
import "./interface/INFTXFeeDistributor.sol";
import "./interface/IPrevNftxContract.sol";
import "./interface/IRewardDistributionToken.sol";
import "./token/ERC20BurnableUpgradeable.sol";
import "./token/ERC20FlashMintUpgradeable.sol";
import "./token/ERC721HolderUpgradeable.sol";
import "./token/ERC1155HolderUpgradeable.sol";
import "./token/IERC721Upgradeable.sol";
import "./token/IERC1155Upgradeable.sol";
import "./util/PausableUpgradeable.sol";
import "./util/SafeMathUpgradeable.sol";
import "./util/ReentrancyGuardUpgradeable.sol";
import "./util/EnumerableSetUpgradeable.sol";
import "hardhat/console.sol";
contract NFTXVaultUpgradeable is
PausableUpgradeable,
ERC20BurnableUpgradeable,
ERC20FlashMintUpgradeable,
ReentrancyGuardUpgradeable,
ERC721HolderUpgradeable,
ERC1155HolderUpgradeable
{
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
uint256 constant base = 10**18;
uint256 public vaultId;
address public manager;
address public assetAddress;
INFTXVaultFactory public vaultFactory;
INFTXEligibility public eligibilityStorage;
uint256 randNonce;
uint256 public mintFee;
uint256 public redeemFee;
uint256 public directRedeemFee;
uint256 public swapFee;
// Purposely putting these on a new slot to make sure they're together.
bool public is1155;
bool public allowAllItems;
bool public enableMint;
bool public enableRedeem;
bool public enableDirectRedeem;
bool public enableSwap;
bool[20] _bool_gap;
string public description;
EnumerableSetUpgradeable.UintSet holdings;
mapping(uint256 => uint256) quantity1155;
event VaultInit(
uint256 indexed vaultId,
address assetAddress,
bool is1155,
bool allowAllItems
);
event ManagerSet(address manager);
event EligibilityDeployed(address eligibilityAddr);
event EnableMintUpdated(bool enabled);
event EnableRedeemUpdated(bool enabled);
event EnableDirectRedeemUpdated(bool enabled);
event EnableSwapUpdated(bool enabled);
event MintFeeUpdated(uint256 mintFee);
event RedeemFeeUpdated(uint256 redeemFee);
event DirectRedeemFeeUpdated(uint256 directRedeemFee);
event SwapFeeUpdated(uint256 swapFee);
event Minted(uint256[] nftIds, uint256[] amounts, address sender);
event Redeemed(uint256[] nftIds, address sender);
event Swapped(
uint256[] nftIds,
uint256[] amounts,
uint256[] specificIds,
address sender
);
constructor() public {
__Pausable_init();
__ERC20_init("", "");
__ERC20Burnable_init_unchained();
__ERC20FlashMint_init();
}
function __NFTXVault_init(
string memory _name,
string memory _symbol,
address _assetAddress,
bool _is1155,
bool _allowAllItems
) public initializer {
__Pausable_init();
__ERC20_init(_name, _symbol);
__ERC20Burnable_init_unchained();
__ERC20FlashMint_init();
assetAddress = _assetAddress;
vaultFactory = INFTXVaultFactory(msg.sender);
vaultId = vaultFactory.numVaults();
is1155 = _is1155;
allowAllItems = _allowAllItems;
emit VaultInit(vaultId, _assetAddress, _is1155, _allowAllItems);
}
function finalizeFund() external virtual {
setManager(address(0));
}
function setVaultFeatures(
bool _enableMint,
bool _enableRedeem,
bool _enableDirectRedeem,
bool _enableSwap
) external virtual {
onlyPrivileged();
enableMint = _enableMint;
enableRedeem = _enableRedeem;
enableDirectRedeem = _enableDirectRedeem;
enableSwap = _enableSwap;
emit EnableMintUpdated(enableMint);
emit EnableRedeemUpdated(enableRedeem);
emit EnableDirectRedeemUpdated(enableDirectRedeem);
emit EnableSwapUpdated(enableSwap);
}
// Should we do defaults?
function setFees(
uint256 _mintFee,
uint256 _redeemFee,
uint256 _directRedeemFee,
uint256 _swapFee
) external virtual {
onlyPrivileged();
mintFee = _mintFee;
redeemFee = _redeemFee;
directRedeemFee = _directRedeemFee;
swapFee = _swapFee;
emit MintFeeUpdated(_mintFee);
emit RedeemFeeUpdated(_redeemFee);
emit DirectRedeemFeeUpdated(_directRedeemFee);
emit SwapFeeUpdated(_swapFee);
}
// This function alls for an easy setup of any eligibility module contract from the EligibilityManager.
// It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow
// a similar interface.
function deployEligibilityStorage(
uint256 moduleIndex,
bytes calldata initData
) external virtual returns (address) {
onlyPrivileged();
INFTXEligibilityManager eligManager = INFTXEligibilityManager(
vaultFactory.eligibilityManager()
);
address _eligibility = eligManager.deployEligibility(
moduleIndex,
initData
);
setEligibilityStorage(_eligibility);
return _eligibility;
}
// This function allows for the manager to set their own arbitrary eligibility contract.
// Once eligiblity is set, it cannot be unset or changed.
function setEligibilityStorage(address _newEligibility) public virtual {
onlyPrivileged();
require(
address(eligibilityStorage) == address(0),
"NFTXVault: eligibility already set"
);
eligibilityStorage = INFTXEligibility(_newEligibility);
// Toggle this to let the contract know to check eligibility now.
allowAllItems = false;
emit EligibilityDeployed(address(_newEligibility));
}
// The manager has control over options like fees and features
function setManager(address _manager) public virtual {
onlyPrivileged();
manager = _manager;
emit ManagerSet(_manager);
}
function mint(
uint256[] calldata tokenIds,
uint256[] calldata amounts
) external virtual returns (uint256) {
return mintTo(tokenIds, amounts, msg.sender);
}
function mintTo(
uint256[] memory tokenIds,
uint256[] memory amounts,
address to
) public virtual nonReentrant returns (uint256) {
onlyOwnerIfPaused(1);
require(enableMint, "Minting not enabled");
require(allValidNFTs(tokenIds), "NFTXVault: not eligible");
uint256 count = receiveNFTs(tokenIds, amounts);
uint256 fee = mintFee.mul(count);
_mint(to, base.mul(count).sub(fee));
_distributeFees(fee);
emit Minted(tokenIds, amounts, to);
return count;
}
function redeem(uint256 amount, uint256[] calldata specificIds)
external
virtual
returns (uint256[] memory)
{
return redeemTo(amount, specificIds, msg.sender);
}
function redeemTo(uint256 amount, uint256[] memory specificIds, address to)
public
virtual
nonReentrant
returns (uint256[] memory)
{
onlyOwnerIfPaused(2);
require(enableRedeem, "Redeeming not enabled");
require(
specificIds.length == 0 || enableDirectRedeem,
"Direct redeem not enabled"
);
uint256 fee = directRedeemFee.mul(specificIds.length).add(
redeemFee.mul(amount.sub(specificIds.length))
);
// We burn all from sender and mint to fee receiver to reduce costs.
_burnFrom(msg.sender, base.mul(amount).add(fee));
_distributeFees(fee);
uint256[] memory redeemedIds = withdrawNFTsTo(amount, specificIds, to);
afterRedeemHook(redeemedIds);
emit Redeemed(redeemedIds, to);
return redeemedIds;
}
function swap(
uint256[] calldata tokenIds,
uint256[] calldata amounts,
uint256[] calldata specificIds
) external virtual nonReentrant returns (uint256[] memory) {
return swapTo(tokenIds, amounts, specificIds, msg.sender);
}
function swapTo(
uint256[] memory tokenIds,
uint256[] memory amounts,
uint256[] memory specificIds,
address to
) public virtual returns (uint256[] memory) {
onlyOwnerIfPaused(3);
require(enableSwap, "Swapping not enabled");
require(
specificIds.length == 0 || enableDirectRedeem,
"Direct redeem not enabled"
);
uint256 count = receiveNFTs(tokenIds, amounts);
uint256 fee = directRedeemFee.mul(specificIds.length).add(
swapFee.mul(count.sub(specificIds.length))
);
// We burn all from sender and mint to fee receiver to reduce costs.
_burnFrom(msg.sender, fee);
_distributeFees(fee);
uint256[] memory ids = withdrawNFTsTo(count, specificIds, to);
emit Swapped(tokenIds, amounts, specificIds, to);
return ids;
}
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes memory data
) public virtual override returns (bool) {
onlyOwnerIfPaused(4);
super.flashLoan(receiver, token, amount, data);
}
function allValidNFTs(uint256[] memory tokenIds)
public
view
returns (bool)
{
// add allow all check here
if (allowAllItems) {
return true;
}
INFTXEligibility _eligibilityStorage = eligibilityStorage;
if (address(_eligibilityStorage) == address(0)) {
return false;
}
return _eligibilityStorage.checkAllEligible(tokenIds);
}
// We set a hook to the eligibility module (if it exists) after redeems in case anything needs to be modified.
function afterRedeemHook(uint256[] memory tokenIds) internal virtual {
INFTXEligibility _eligibilityStorage = eligibilityStorage;
if (address(_eligibilityStorage) == address(0)) {
return;
}
_eligibilityStorage.afterRedeemHook(tokenIds);
}
function receiveNFTs(uint256[] memory tokenIds, uint256[] memory amounts)
internal
virtual
returns (uint256)
{
if (is1155) {
// This is technically a check, so placing it before the effect.
IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(
msg.sender,
address(this),
tokenIds,
amounts,
""
);
uint256 count;
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
uint256 amount = amounts[i];
if (quantity1155[tokenId] == 0) {
holdings.add(tokenId);
}
quantity1155[tokenId] = quantity1155[tokenId].add(amount);
count = count.add(amount);
}
return count;
} else {
IERC721Upgradeable erc721 = IERC721Upgradeable(assetAddress);
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
erc721.safeTransferFrom(msg.sender, address(this), tokenId);
holdings.add(tokenId);
}
return tokenIds.length;
}
}
function withdrawNFTsTo(
uint256 amount,
uint256[] memory specificIds,
address to
) internal virtual returns (uint256[] memory) {
bool _is1155 = is1155;
address _assetAddress = assetAddress;
uint256[] memory redeemedIds = new uint256[](amount);
for (uint256 i = 0; i < amount; i++) {
uint256 tokenId = i < specificIds.length
? specificIds[i]
: getRandomTokenIdFromFund();
redeemedIds[i] = tokenId;
if (_is1155) {
IERC1155Upgradeable(_assetAddress).safeTransferFrom(
address(this),
to,
tokenId,
1,
""
);
quantity1155[tokenId] = quantity1155[tokenId].sub(1);
if (quantity1155[tokenId] == 0) {
holdings.remove(tokenId);
}
} else {
IERC721Upgradeable(_assetAddress).safeTransferFrom(
address(this),
to,
tokenId
);
holdings.remove(tokenId);
}
}
return redeemedIds;
}
function _distributeFees(uint256 amount) internal virtual {
// Mint fees directly to the distributor and distribute.
if (amount > 0) {
address feeReceiver = vaultFactory.feeReceiver();
_mint(feeReceiver, amount);
INFTXFeeDistributor(feeReceiver).distribute(vaultId);
}
}
function getRandomTokenIdFromFund() internal virtual returns (uint256) {
uint256 randomIndex = getPseudoRand(holdings.length());
return holdings.at(randomIndex);
}
function getPseudoRand(uint256 modulus) internal virtual returns (uint256) {
randNonce += 1;
return
uint256(
keccak256(
abi.encodePacked(blockhash(block.number - 1), randNonce)
)
) %
modulus;
}
function onlyPrivileged() internal view {
if (manager == address(0)) {
require(msg.sender == owner(), "Not owner");
} else {
require(msg.sender == manager, "Not manager");
}
}
// TODO: recount this.
uint256[25] ___gap;
} | 3,228 | 440 | 2 | 1. [H-03] getRandomTokenIdFromFund yields wrong probabilities for ERC1155 (Predictable randomness)
NFTXVaultUpgradeable.`getRandomTokenIdFromFund` does not work with ERC1155 as it does not take the deposited quantity1155 into account.
2. [H-04] NFTXLPStaking Is Subject To A Flash Loan Attack That Can Steal Nearly All Rewards/Fees That Have Accrued For A Particular Vault (flash loan)
The fact that the NFTXVaultUpgradeable contract contains a native `flashLoan` function makes this attack that much easier, although it would still be possible even without that due to flashloans on Uniswap, or wherever else the nftX token is found.
3. [M-06] Manager can grief with fees in `withdrawNFTsTo` (Front-run, Unprotected `setFees` function)
The fees in NFTXVaultUpgradeable can be set arbitrarily high (no restriction in setFees).
The manager can front-run mints and set a huge fee (for example fee = base) which transfers user's NFTs to the vault but doesn't mint any pool share tokens in return for the user.
4. [M-09] The direct redeem fee can be circumvented (DoS, Unchecked external valls)
Since the random NFT is determined in the same transaction a payment or swap is being executed, a malicious actor can revert a transaction if they did not get the NFT they wanted. Combined with utilizing Flashbots miners which do not publish transactions which revert with FlashbotsCheckAndSend, there would be no cost to constantly attempting this every block or after the nonce is updated from `getPseudoRand()`.
| 4 |
83_ConvexStakingWrapper.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./external/ConvexInterfaces.sol";
import "./interfaces/IConcurRewardClaim.sol";
import "./MasterChef.sol";
contract ConvexStakingWrapper is Ownable, ReentrancyGuard, Pausable {
using SafeERC20 for IERC20;
struct RewardType {
address token;
address pool;
uint128 integral;
uint128 remaining;
}
struct Reward {
uint128 integral;
}
//constants/immutables
address public constant convexBooster =
address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
address public constant crv =
address(0xD533a949740bb3306d119CC777fa900bA034cd52);
address public constant cvx =
address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
uint256 public constant CRV_INDEX = 0;
uint256 public constant CVX_INDEX = 1;
uint256 public constant VOTECYCLE_START = 1645002000;
//Feb 16 2022 09:00:00 GMT+0000
MasterChef public immutable masterChef;
//convex rewards
mapping(uint256 => address) public convexPool;
mapping(uint256 => RewardType[]) public rewards;
mapping(uint256 => mapping(uint256 => mapping(address => Reward)))
public userReward;
mapping(uint256 => mapping(address => uint256)) public registeredRewards;
//management
address public treasury;
IConcurRewardClaim public claimContract;
struct Deposit {
uint64 epoch;
uint192 amount;
}
struct WithdrawRequest {
uint64 epoch;
uint192 amount;
}
mapping(address => uint256) public pids;
mapping(uint256 => mapping(address => Deposit)) public deposits;
mapping(uint256 => mapping(address => WithdrawRequest)) public withdrawRequest;
event Deposited(address indexed _user, uint256 _amount);
event Withdrawn(address indexed _user, uint256 _amount);
constructor(address _treasury, MasterChef _masterChef) {
treasury = _treasury;
masterChef = _masterChef;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function changeTreasury(address _treasury) external onlyOwner {
treasury = _treasury;
}
function setRewardPool(address _claimContract) external onlyOwner {
claimContract = IConcurRewardClaim(_claimContract);
}
/// @notice function to bootstrap the reward pool and extra rewards of convex booster
/// @dev should be able to be called more than once
/// @param _pid pid of the curve lp. same as convex booster pid
function addRewards(uint256 _pid) public {
address mainPool = IRewardStaking(convexBooster)
.poolInfo(_pid)
.crvRewards;
if (rewards[_pid].length == 0) {
pids[IRewardStaking(convexBooster).poolInfo(_pid).lptoken] = _pid;
convexPool[_pid] = mainPool;
rewards[_pid].push(
RewardType({
token: crv,
pool: mainPool,
integral: 0,
remaining: 0
})
);
rewards[_pid].push(
RewardType({
token: cvx,
pool: address(0),
integral: 0,
remaining: 0
})
);
registeredRewards[_pid][crv] = CRV_INDEX + 1;
//mark registered at index+1
registeredRewards[_pid][cvx] = CVX_INDEX + 1;
//mark registered at index+1
}
uint256 extraCount = IRewardStaking(mainPool).extraRewardsLength();
for (uint256 i = 0; i < extraCount; i++) {
address extraPool = IRewardStaking(mainPool).extraRewards(i);
address extraToken = IRewardStaking(extraPool).rewardToken();
if (extraToken == cvx) {
//no-op for cvx, crv rewards
rewards[_pid][CVX_INDEX].pool = extraPool;
} else if (registeredRewards[_pid][extraToken] == 0) {
//add new token to list
rewards[_pid].push(
RewardType({
token: IRewardStaking(extraPool).rewardToken(),
pool: extraPool,
integral: 0,
remaining: 0
})
);
registeredRewards[_pid][extraToken] = rewards[_pid].length;
//mark registered at index+1
}
}
}
function rewardLength(uint256 _pid) external view returns (uint256) {
return rewards[_pid].length;
}
function _getDepositedBalance(uint256 _pid, address _account)
internal
view
virtual
returns (uint256)
{
return deposits[_pid][_account].amount;
}
function _getTotalSupply(uint256 _pid)
internal
view
virtual
returns (uint256)
{
return IRewardStaking(convexPool[_pid]).balanceOf(address(this));
}
function _calcRewardIntegral(
uint256 _pid,
uint256 _index,
address _account,
uint256 _balance,
uint256 _supply
) internal {
RewardType memory reward = rewards[_pid][_index];
//get difference in balance and remaining rewards
//getReward is unguarded so we use remaining to keep track of how much was actually claimed
uint256 bal = IERC20(reward.token).balanceOf(address(this));
uint256 d_reward = bal - reward.remaining;
// send 20 % of cvx / crv reward to treasury
if (reward.token == cvx || reward.token == crv) {
IERC20(reward.token).transfer(treasury, d_reward / 5);
d_reward = (d_reward * 4) / 5;
}
IERC20(reward.token).transfer(address(claimContract), d_reward);
if (_supply > 0 && d_reward > 0) {
reward.integral =
reward.integral +
uint128((d_reward * 1e20) / _supply);
}
//update user integrals
uint256 userI = userReward[_pid][_index][_account].integral;
if (userI < reward.integral) {
userReward[_pid][_index][_account].integral = reward.integral;
claimContract.pushReward(
_account,
reward.token,
(_balance * (reward.integral - userI)) / 1e20
);
}
//update remaining reward here since balance could have changed if claiming
if (bal != reward.remaining) {
reward.remaining = uint128(bal);
}
rewards[_pid][_index] = reward;
}
function _checkpoint(uint256 _pid, address _account) internal {
//if shutdown, no longer checkpoint in case there are problems
if (paused()) return;
uint256 supply = _getTotalSupply(_pid);
uint256 depositedBalance = _getDepositedBalance(_pid, _account);
IRewardStaking(convexPool[_pid]).getReward(address(this), true);
uint256 rewardCount = rewards[_pid].length;
for (uint256 i = 0; i < rewardCount; i++) {
_calcRewardIntegral(_pid, i, _account, depositedBalance, supply);
}
}
/// @notice deposit curve lp token
/// @dev should approve curve lp token to this address before calling this function
/// @param _pid pid to deposit, uses same pid as convex booster
/// @param _amount amount to withdraw
function deposit(uint256 _pid, uint256 _amount)
external
whenNotPaused
nonReentrant
{
_checkpoint(_pid, msg.sender);
deposits[_pid][msg.sender].epoch = currentEpoch();
deposits[_pid][msg.sender].amount += uint192(_amount);
if (_amount > 0) {
IERC20 lpToken = IERC20(
IRewardStaking(convexPool[_pid]).poolInfo(_pid).lptoken
);
lpToken.safeTransferFrom(msg.sender, address(this), _amount);
lpToken.safeApprove(convexBooster, _amount);
IConvexDeposits(convexBooster).deposit(_pid, _amount, true);
lpToken.safeApprove(convexBooster, 0);
uint256 pid = masterChef.pid(address(lpToken));
masterChef.deposit(msg.sender, pid, _amount);
}
emit Deposited(msg.sender, _amount);
}
/// @notice withdraw curve lp token
/// @dev should request withdraw before calling this function
/// @param _pid pid to withdraw, uses same pid as convex booster
/// @param _amount amount to withdraw
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
WithdrawRequest memory request = withdrawRequest[_pid][msg.sender];
require(request.epoch < currentEpoch() && deposits[_pid][msg.sender].epoch + 1 < currentEpoch(), "wait");
require(request.amount >= _amount, "too much");
_checkpoint(_pid, msg.sender);
deposits[_pid][msg.sender].amount -= uint192(_amount);
if (_amount > 0) {
IRewardStaking(convexPool[_pid]).withdrawAndUnwrap(_amount, false);
IERC20 lpToken = IERC20(
IRewardStaking(convexPool[_pid]).poolInfo(_pid).lptoken
);
lpToken.safeTransfer(msg.sender, _amount);
uint256 pid = masterChef.pid(address(lpToken));
masterChef.withdraw(msg.sender, pid, _amount);
}
delete withdrawRequest[_pid][msg.sender];
//events
emit Withdrawn(msg.sender, _amount);
}
/// @notice epoch for voting cycle
/// @return returns the epoch in uint64 type
function currentEpoch() public view returns(uint64) {
return uint64((block.timestamp - VOTECYCLE_START) / 2 weeks) + 1;
}
/// @notice request withdraw to be eligible for withdrawal after currentEpoch
/// @dev prior withdrawal request will be overwritten
/// @param _pid pid to withdraw
/// @param _amount amount to request withdrawal
function requestWithdraw(uint256 _pid, uint256 _amount) external {
require(_amount <= uint256(deposits[_pid][msg.sender].amount), "too much");
withdrawRequest[_pid][msg.sender] = WithdrawRequest({
epoch : currentEpoch(),
amount : uint192(_amount)
});
}
} | 2,485 | 298 | 1 | 1. H-04: ConvexStakingWrapper, StakingRewards Wrong implementation will send concur rewards to the wrong receiver. L246
In `deposit` function, (Lack of Input Validation)
2. H-06: ConvexStakingWrapper.sol#_calcRewardIntegral Wrong implementation can disrupt rewards calculation and distribution. L175-L204
In `_calcRewardIntegral` function
3. H-09: deposit in ConvexStakingWrapper will most certainly revert. L94-L99
In `addRewards` function
4. H-10: ConvexStakingWrapper.exitShelter() Will Lock LP Tokens, Preventing Users From Withdrawing L121-L130
5. H-11: ConvexStakingWrapper._calcRewardIntegral() Can Be Manipulated To Steal Tokens From Other Pools L216-259
6. [M-08] Donated Tokens Cannot Be Recovered If A Shelter Is Deactivated (Initialization)
The `owner` of the ConvexStakingWrapper.sol contract can initiate the shelter whereby LP tokens are sent to the Shelter.sol contract.
7. [M-11] ConvexStakingWrapper.enterShelter() may erroneously overwrite amountInShelter leading to Locked Tokens
The shelter mechanism provides emergency functionality in an effort to protect users’ funds. The `enterShelter` function will withdraw all LP tokens from the pool, transfer them to the shelter contract and activate the shelter for the target LP token. If this function is called again on the same LP token, the amountInShelter value is overwritten, potentially by the zero amount. As a result its possible that the shelter is put in a state where no users can withdraw from it or only a select few users with a finite number of shares are able to. Once the shelter has passed its grace period, these tokens may forever be locked in the shelter contract.
8. [M-22] If The Staking Token Exists In Both StakingRewards.sol And ConvexStakingWrapper.sol Then It Will Be Possible To Continue Claiming Concur Rewards After The Shelter Has Been Activated
9. [M-24] Rewards distribution can be disrupted by a early user (Rewards distribution)
In `_calcRewardIntegral` function
10. [M-25] ConvexStakingWrapper#deposit() depositors may lose their funds when the _amount is huge
11.[M-29] ConvexStakingWrapper deposits and withdraws will frequently be disabled if a token that doesn't allow zero value transfers will be added as a reward one
(Reentrancy) `withdraw` and `deposit` | 11 |
18_LendingPair.sol | // SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2021 0xdev0 - All rights reserved
// https://twitter.com/0xdev0
pragma solidity ^0.8.0;
import './interfaces/IERC20.sol';
import './interfaces/ILPTokenMaster.sol';
import './interfaces/ILendingPair.sol';
import './interfaces/IController.sol';
import './interfaces/IRewardDistribution.sol';
import './interfaces/IInterestRateModel.sol';
import './external/Math.sol';
import './external/Ownable.sol';
import './external/Address.sol';
import './external/Clones.sol';
import './external/ERC20.sol';
import './TransferHelper.sol';
contract LendingPair is TransferHelper {
// Prevents division by zero and other undesirable behaviour
uint public constant MIN_RESERVE = 1000;
using Address for address;
using Clones for address;
mapping (address => mapping (address => uint)) public debtOf;
mapping (address => mapping (address => uint)) public accountInterestSnapshot;
mapping (address => uint) public cumulativeInterestRate;
mapping (address => uint) public totalDebt;
mapping (address => IERC20) public lpToken;
IController public controller;
address public tokenA;
address public tokenB;
uint public lastBlockAccrued;
event Liquidation(
address indexed account,
address indexed repayToken,
address indexed supplyToken,
uint repayAmount,
uint supplyAmount
);
event Deposit(address indexed account, address indexed token, uint amount);
event Withdraw(address indexed token, uint amount);
event Borrow(address indexed token, uint amount);
event Repay(address indexed account, address indexed token, uint amount);
receive() external payable {}
function initialize(
address _lpTokenMaster,
address _controller,
IERC20 _tokenA,
IERC20 _tokenB
) external {
require(address(tokenA) == address(0), "LendingPair: already initialized");
require(address(_tokenA) != address(0) && address(_tokenB) != address(0), "LendingPair: cannot be ZERO address");
controller = IController(_controller);
tokenA = address(_tokenA);
tokenB = address(_tokenB);
lastBlockAccrued = block.number;
lpToken[tokenA] = _createLpToken(_lpTokenMaster);
lpToken[tokenB] = _createLpToken(_lpTokenMaster);
}
function depositRepay(address _account, address _token, uint _amount) external {
_validateToken(_token);
accrueAccount(_account);
_depositRepay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function depositRepayETH(address _account) external payable {
accrueAccount(_account);
_depositRepay(_account, address(WETH), msg.value);
_depositWeth();
}
function deposit(address _account, address _token, uint _amount) external {
_validateToken(_token);
accrueAccount(_account);
_deposit(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function withdrawBorrow(address _token, uint _amount) external {
_validateToken(_token);
accrueAccount(msg.sender);
_withdrawBorrow(_token, _amount);
_safeTransfer(IERC20(_token), msg.sender, _amount);
}
function withdrawBorrowETH(uint _amount) external {
accrueAccount(msg.sender);
_withdrawBorrow(address(WETH), _amount);
_wethWithdrawTo(msg.sender, _amount);
_checkMinReserve(address(WETH));
}
function withdraw(address _token, uint _amount) external {
_validateToken(_token);
accrueAccount(msg.sender);
_withdraw(_token, _amount);
_safeTransfer(IERC20(_token), msg.sender, _amount);
}
function withdrawAll(address _token) external {
_validateToken(_token);
accrueAccount(msg.sender);
uint amount = lpToken[address(_token)].balanceOf(msg.sender);
_withdraw(_token, amount);
_safeTransfer(IERC20(_token), msg.sender, amount);
}
function withdrawAllETH() external {
accrueAccount(msg.sender);
uint amount = lpToken[address(WETH)].balanceOf(msg.sender);
_withdraw(address(WETH), amount);
_wethWithdrawTo(msg.sender, amount);
}
function borrow(address _token, uint _amount) external {
_validateToken(_token);
accrueAccount(msg.sender);
_borrow(_token, _amount);
_safeTransfer(IERC20(_token), msg.sender, _amount);
}
function repayAll(address _account, address _token) external {
_validateToken(_token);
accrueAccount(_account);
uint amount = debtOf[_token][_account];
_repay(_account, _token, amount);
_safeTransferFrom(_token, msg.sender, amount);
}
function repayAllETH(address _account) external payable {
accrueAccount(_account);
uint amount = debtOf[address(WETH)][_account];
require(msg.value >= amount, "LendingPair: insufficient ETH deposit");
_depositWeth();
_repay(_account, address(WETH), amount);
uint refundAmount = msg.value > amount ? (msg.value - amount) : 0;
if (refundAmount > 0) {
_wethWithdrawTo(msg.sender, refundAmount);
}
}
function repay(address _account, address _token, uint _amount) external {
_validateToken(_token);
accrueAccount(_account);
_repay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function accrue() public {
if (lastBlockAccrued < block.number) {
_accrueInterest(tokenA);
_accrueInterest(tokenB);
lastBlockAccrued = block.number;
}
}
function accrueAccount(address _account) public {
_distributeReward(_account);
accrue();
_accrueAccountInterest(_account);
if (_account != feeRecipient()) {
_accrueAccountInterest(feeRecipient());
}
}
function accountHealth(address _account) public view returns(uint) {
if (debtOf[tokenA][_account] == 0 && debtOf[tokenB][_account] == 0) {
return controller.LIQ_MIN_HEALTH();
}
uint totalAccountSupply = _supplyCredit(_account, tokenA, tokenA) + _supplyCredit(_account, tokenB, tokenA);
uint totalAccountBorrrow = _borrowBalance(_account, tokenA, tokenA) + _borrowBalance(_account, tokenB, tokenA);
return totalAccountSupply * 1e18 / totalAccountBorrrow;
}
// Get borow balance converted to the units of _returnToken
function borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_borrowedToken);
_validateToken(_returnToken);
return _borrowBalance(_account, _borrowedToken, _returnToken);
}
function supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_suppliedToken);
_validateToken(_returnToken);
return _supplyBalance(_account, _suppliedToken, _returnToken);
}
function supplyRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return controller.interestRateModel().supplyRatePerBlock(ILendingPair(address(this)), _token);
}
function borrowRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return _borrowRatePerBlock(_token);
}
// Sell collateral to reduce debt and increase accountHealth
// Set _repayAmount to uint(-1) to repay all debt, inc. pending interest
function liquidateAccount(
address _account,
address _repayToken,
uint _repayAmount,
uint _minSupplyOutput
) external {
// Input validation and adjustments
_validateToken(_repayToken);
address supplyToken = _repayToken == tokenA ? tokenB : tokenA;
// Check account is underwater after interest
_accrueAccountInterest(_account);
_accrueAccountInterest(feeRecipient());
uint health = accountHealth(_account);
require(health < controller.LIQ_MIN_HEALTH(), "LendingPair: account health > LIQ_MIN_HEALTH");
// Calculate balance adjustments
_repayAmount = Math.min(_repayAmount, debtOf[_repayToken][_account]);
uint supplyDebt = _convertTokenValues(_repayToken, supplyToken, _repayAmount);
uint callerFee = supplyDebt * controller.liqFeeCaller(_repayToken) / 100e18;
uint systemFee = supplyDebt * controller.liqFeeSystem(_repayToken) / 100e18;
uint supplyBurn = supplyDebt + callerFee + systemFee;
uint supplyOutput = supplyDebt + callerFee;
require(supplyOutput >= _minSupplyOutput, "LendingPair: supplyOutput >= _minSupplyOutput");
// Adjust balances
_burnSupply(supplyToken, _account, supplyBurn);
_mintSupply(supplyToken, feeRecipient(), systemFee);
_burnDebt(_repayToken, _account, _repayAmount);
// Settle token transfers
_safeTransferFrom(_repayToken, msg.sender, _repayAmount);
_safeTransfer(IERC20(supplyToken), msg.sender, supplyOutput);
emit Liquidation(_account, _repayToken, supplyToken, _repayAmount, supplyOutput);
}
function pendingSupplyInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
uint newInterest = _newInterest(lpToken[_token].balanceOf(_account), _token, _account);
return newInterest * _lpRate(_token) / 100e18;
}
function pendingBorrowInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
return _pendingBorrowInterest(_token, _account);
}
function feeRecipient() public view returns(address) {
return controller.feeRecipient();
}
function checkAccountHealth(address _account) public view {
uint health = accountHealth(_account);
require(health >= controller.LIQ_MIN_HEALTH(), "LendingPair: insufficient accountHealth");
}
function convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) external view returns(uint) {
_validateToken(_fromToken);
_validateToken(_toToken);
return _convertTokenValues(_fromToken, _toToken, _inputAmount);
}
function _depositRepay(address _account, address _token, uint _amount) internal {
uint debt = debtOf[_token][_account];
uint repayAmount = debt > _amount ? _amount : debt;
if (repayAmount > 0) {
_repay(_account, _token, repayAmount);
}
uint depositAmount = _amount - repayAmount;
if (depositAmount > 0) {
_deposit(_account, _token, depositAmount);
}
}
function _withdrawBorrow(address _token, uint _amount) internal {
uint supplyAmount = lpToken[_token].balanceOf(msg.sender);
uint withdrawAmount = supplyAmount > _amount ? _amount : supplyAmount;
if (withdrawAmount > 0) {
_withdraw(_token, withdrawAmount);
}
uint borrowAmount = _amount - withdrawAmount;
if (borrowAmount > 0) {
_borrow(_token, borrowAmount);
}
}
function _distributeReward(address _account) internal {
IRewardDistribution rewardDistribution = controller.rewardDistribution();
if (address(rewardDistribution) != address(0)) {
rewardDistribution.distributeReward(_account, tokenA);
rewardDistribution.distributeReward(_account, tokenB);
}
}
function _mintSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].mint(_account, _amount);
}
}
function _burnSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].burn(_account, _amount);
}
}
function _mintDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] += _amount;
totalDebt[_token] += _amount;
}
function _burnDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] -= _amount;
totalDebt[_token] -= _amount;
}
function _accrueAccountInterest(address _account) internal {
uint lpBalanceA = lpToken[tokenA].balanceOf(_account);
uint lpBalanceB = lpToken[tokenB].balanceOf(_account);
_accrueAccountSupply(tokenA, lpBalanceA, _account);
_accrueAccountSupply(tokenB, lpBalanceB, _account);
_accrueAccountDebt(tokenA, _account);
_accrueAccountDebt(tokenB, _account);
accountInterestSnapshot[tokenA][_account] = cumulativeInterestRate[tokenA];
accountInterestSnapshot[tokenB][_account] = cumulativeInterestRate[tokenB];
}
function _accrueAccountSupply(address _token, uint _amount, address _account) internal {
if (_amount > 0) {
uint supplyInterest = _newInterest(_amount, _token, _account);
uint newSupplyAccount = supplyInterest * _lpRate(_token) / 100e18;
uint newSupplySystem = supplyInterest * _systemRate(_token) / 100e18;
_mintSupply(_token, _account, newSupplyAccount);
_mintSupply(_token, feeRecipient(), newSupplySystem);
}
}
function _accrueAccountDebt(address _token, address _account) internal {
if (debtOf[_token][_account] > 0) {
uint newDebt = _pendingBorrowInterest(_token, _account);
_mintDebt(_token, _account, newDebt);
}
}
function _withdraw(address _token, uint _amount) internal {
lpToken[address(_token)].burn(msg.sender, _amount);
checkAccountHealth(msg.sender);
emit Withdraw(_token, _amount);
}
function _borrow(address _token, uint _amount) internal {
require(lpToken[address(_token)].balanceOf(msg.sender) == 0, "LendingPair: cannot borrow supplied token");
_mintDebt(_token, msg.sender, _amount);
_checkBorrowLimits(_token, msg.sender);
checkAccountHealth(msg.sender);
emit Borrow(_token, _amount);
}
function _repay(address _account, address _token, uint _amount) internal {
_burnDebt(_token, _account, _amount);
emit Repay(_account, _token, _amount);
}
function _deposit(address _account, address _token, uint _amount) internal {
_checkOracleSupport(tokenA);
_checkOracleSupport(tokenB);
require(debtOf[_token][_account] == 0, "LendingPair: cannot deposit borrowed token");
_mintSupply(_token, _account, _amount);
_checkDepositLimit(_token);
emit Deposit(_account, _token, _amount);
}
function _accrueInterest(address _token) internal {
uint blocksElapsed = block.number - lastBlockAccrued;
uint newInterest = _borrowRatePerBlock(_token) * blocksElapsed;
cumulativeInterestRate[_token] += newInterest;
}
function _createLpToken(address _lpTokenMaster) internal returns(IERC20) {
ILPTokenMaster newLPToken = ILPTokenMaster(_lpTokenMaster.clone());
newLPToken.initialize();
return IERC20(newLPToken);
}
function _safeTransfer(IERC20 _token, address _recipient, uint _amount) internal {
if (_amount > 0) {
bool success = _token.transfer(_recipient, _amount);
require(success, "LendingPair: transfer failed");
_checkMinReserve(address(_token));
}
}
function _wethWithdrawTo(address _to, uint _amount) internal override {
if (_amount > 0) {
TransferHelper._wethWithdrawTo(_to, _amount);
_checkMinReserve(address(WETH));
}
}
function _borrowRatePerBlock(address _token) internal view returns(uint) {
return controller.interestRateModel().borrowRatePerBlock(ILendingPair(address(this)), _token);
}
function _pendingBorrowInterest(address _token, address _account) internal view returns(uint) {
return _newInterest(debtOf[_token][_account], _token, _account);
}
function _borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_borrowedToken, _returnToken, debtOf[_borrowedToken][_account]);
}
// Get supply balance converted to the units of _returnToken
function _supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_suppliedToken, _returnToken, lpToken[_suppliedToken].balanceOf(_account));
}
function _supplyCredit(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _supplyBalance(_account, _suppliedToken, _returnToken) * controller.colFactor(_suppliedToken) / 100e18;
}
function _convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) internal view returns(uint) {
uint priceFrom = controller.tokenPrice(_fromToken) * 1e18 / 10 ** IERC20(_fromToken).decimals();
uint priceTo = controller.tokenPrice(_toToken) * 1e18 / 10 ** IERC20(_toToken).decimals();
return _inputAmount * priceFrom / priceTo;
}
function _validateToken(address _token) internal view {
require(_token == tokenA || _token == tokenB, "LendingPair: invalid token");
}
function _checkOracleSupport(address _token) internal view {
require(controller.tokenSupported(_token), "LendingPair: token not supported");
}
function _checkMinReserve(address _token) internal view {
require(IERC20(_token).balanceOf(address(this)) >= MIN_RESERVE, "LendingPair: below MIN_RESERVE");
}
function _checkDepositLimit(address _token) internal view {
require(controller.depositsEnabled(), "LendingPair: deposits disabled");
uint depositLimit = controller.depositLimit(address(this), _token);
if (depositLimit > 0) {
require((lpToken[_token].totalSupply()) <= depositLimit, "LendingPair: deposit limit reached");
}
}
function _checkBorrowLimits(address _token, address _account) internal view {
require(controller.borrowingEnabled(), "LendingPair: borrowing disabled");
uint accountBorrowUSD = debtOf[_token][_account] * controller.tokenPrice(_token) / 1e18;
require(accountBorrowUSD >= controller.minBorrowUSD(), "LendingPair: borrow amount below minimum");
uint borrowLimit = controller.borrowLimit(address(this), _token);
if (borrowLimit > 0) {
require(totalDebt[_token] <= borrowLimit, "LendingPair: borrow limit reached");
}
}
function _systemRate(address _token) internal view returns(uint) {
return controller.interestRateModel().systemRate(ILendingPair(address(this)), _token);
}
function _lpRate(address _token) internal view returns(uint) {
return 100e18 - _systemRate(_token);
}
function _newInterest(uint _balance, address _token, address _account) internal view returns(uint) {
return _balance * (cumulativeInterestRate[_token] - accountInterestSnapshot[_token][_account]) / 100e18;
}
} | 4,587 | 578 | 0 | 1. H-01: Reward computation is wrong (Precision Control)
The LendingPair.`accrueAccount` function distributes rewards before updating the cumulative supply / borrow indexes as well as the index + balance for the user (by minting supply tokens / debt). This means the percentage of the user's balance to the total is not correct as the total can be updated several times in between.
2. H-02: LendingPair.liquidateAccount does not accrue and update cumulativeInterestRate
The LendingPair.`liquidateAccount` function does not accrue and update the cumulativeInterestRate first, it only calls _accrueAccountInterest which does not update and instead uses the old cumulativeInterestRate.
3. H-03: LendingPair.liquidateAccount fails if tokens are lent out
The LendingPair.`liquidateAccount` function tries to pay out underlying supply tokens to the liquidator using _safeTransfer(IERC20(supplyToken), msg.sender, supplyOutput) but there's no reason why there should be enough supplyOutput amount in the contract, the contract only ensures minReserve. | 3 |
25_CompositeMultiOracle.sol | // SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.1;
import "../../utils/access/AccessControl.sol";
import "../../interfaces/vault/IOracle.sol";
import "../../math/CastBytes32Bytes6.sol";
/**
* @title CompositeMultiOracle
*/
contract CompositeMultiOracle is IOracle, AccessControl {
using CastBytes32Bytes6 for bytes32;
uint8 public constant override decimals = 18;
// All prices are converted to 18 decimals
event SourceSet(bytes6 indexed baseId, bytes6 indexed quoteId, address indexed source);
event PathSet(bytes6 indexed baseId, bytes6 indexed quoteId, bytes6[] indexed path);
struct Source {
address source;
uint8 decimals;
}
mapping(bytes6 => mapping(bytes6 => Source)) public sources;
mapping(bytes6 => mapping(bytes6 => bytes6[])) public paths;
/**
* @notice Set or reset an oracle source
*/
function setSource(bytes6 base, bytes6 quote, address source) external auth {
_setSource(base, quote, source);
}
/**
* @notice Set or reset a number of oracle sources
*/
function setSources(bytes6[] memory bases, bytes6[] memory quotes, address[] memory sources_) external auth {
require(
bases.length == quotes.length &&
bases.length == sources_.length,
"Mismatched inputs"
);
for (uint256 i = 0; i < bases.length; i++) {
_setSource(bases[i], quotes[i], sources_[i]);
}
}
/**
* @notice Set or reset an price path
*/
function setPath(bytes6 base, bytes6 quote, bytes6[] memory path) external auth {
_setPath(base, quote, path);
}
/**
* @notice Set or reset a number of price paths
*/
function setPaths(bytes6[] memory bases, bytes6[] memory quotes, bytes6[][] memory paths_) external auth {
require(
bases.length == quotes.length &&
bases.length == paths_.length,
"Mismatched inputs"
);
for (uint256 i = 0; i < bases.length; i++) {
_setPath(bases[i], quotes[i], paths_[i]);
}
}
/**
* @notice Retrieve the value of the amount at the latest oracle price.
* @return value
*/
function peek(bytes32 base, bytes32 quote, uint256 amount)
external view virtual override
returns (uint256 value, uint256 updateTime)
{
uint256 price = 1e18;
bytes6 base_ = base.b6();
bytes6 quote_ = quote.b6();
bytes6[] memory path = paths[base_][quote_];
for (uint256 p = 0; p < path.length; p++) {
(price, updateTime) = _peek(base_, path[p], price, updateTime);
base_ = path[p];
}
(price, updateTime) = _peek(base_, quote_, price, updateTime);
value = price * amount / 1e18;
}
/**
* @notice Retrieve the value of the amount at the latest oracle price.. Same as `peek` for this oracle.
* @return value
*/
function get(bytes32 base, bytes32 quote, uint256 amount)
external virtual override
returns (uint256 value, uint256 updateTime)
{
uint256 price = 1e18;
bytes6 base_ = base.b6();
bytes6 quote_ = quote.b6();
bytes6[] memory path = paths[base_][quote_];
for (uint256 p = 0; p < path.length; p++) {
(price, updateTime) = _get(base_, path[p], price, updateTime);
base_ = path[p];
}
(price, updateTime) = _get(base_, quote_, price, updateTime);
value = price * amount / 1e18;
}
function _peek(bytes6 base, bytes6 quote, uint256 priceIn, uint256 updateTimeIn)
private view returns (uint priceOut, uint updateTimeOut)
{
Source memory source = sources[base][quote];
require (source.source != address(0), "Source not found");
(priceOut, updateTimeOut) = IOracle(source.source).peek(base, quote, 10 ** source.decimals);
// Get price for one unit
priceOut = priceIn * priceOut / (10 ** source.decimals);
// Fixed point according to decimals
updateTimeOut = (updateTimeOut < updateTimeIn) ? updateTimeOut : updateTimeIn;
// Take the oldest update time
}
function _get(bytes6 base, bytes6 quote, uint256 priceIn, uint256 updateTimeIn)
private returns (uint priceOut, uint updateTimeOut)
{
Source memory source = sources[base][quote];
require (source.source != address(0), "Source not found");
(priceOut, updateTimeOut) = IOracle(source.source).get(base, quote, 10 ** source.decimals);
// Get price for one unit
priceOut = priceIn * priceOut / (10 ** source.decimals);
// Fixed point according to decimals
updateTimeOut = (updateTimeOut < updateTimeIn) ? updateTimeOut : updateTimeIn;
// Take the oldest update time
}
function _setSource(bytes6 base, bytes6 quote, address source) internal {
uint8 decimals_ = IOracle(source).decimals();
require (decimals_ <= 18, "Unsupported decimals");
sources[base][quote] = Source({
source: source,
decimals: decimals_
});
emit SourceSet(base, quote, source);
}
function _setPath(bytes6 base, bytes6 quote, bytes6[] memory path) internal {
bytes6 base_ = base;
for (uint256 p = 0; p < path.length; p++) {
require (sources[base_][path[p]].source != address(0), "Source not found");
base_ = path[p];
}
paths[base][quote] = path;
emit PathSet(base, quote, path);
}
} | 1,354 | 157 | 1 | H-01: CompositeMultiOracle returns wrong decimals for prices? (Unchecked return values)
The CompositeMultiOracle.peek/get functions seem to return wrong prices. It's unclear what decimals source.decimals refers to in this case. Does it refer to source.source token decimals? `_peek` function | 1 |
14_SushiYieldSource.sol | // SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import { IYieldSource } from "@pooltogether/yield-source-interface/contracts/IYieldSource.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ISushiBar.sol";
import "./ISushi.sol";
/// @title A pooltogether yield source for sushi token
/// @author Steffel Fenix
contract SushiYieldSource is IYieldSource {
using SafeMath for uint256;
ISushiBar public immutable sushiBar;
ISushi public immutable sushiAddr;
mapping(address => uint256) public balances;
constructor(ISushiBar _sushiBar, ISushi _sushiAddr) public {
sushiBar = _sushiBar;
sushiAddr = _sushiAddr;
}
/// @notice Returns the ERC20 asset token used for deposits.
/// @return The ERC20 asset token
function depositToken() public view override returns (address) {
return address(sushiAddr);
}
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function balanceOfToken(address addr) public override returns (uint256) {
if (balances[addr] == 0) return 0;
uint256 totalShares = sushiBar.totalSupply();
uint256 barSushiBalance = sushiAddr.balanceOf(address(sushiBar));
return balances[addr].mul(barSushiBalance).div(totalShares);
}
/// @notice Allows assets to be supplied on other user's behalf using the `to` param.
/// @param amount The amount of `token()` to be supplied
/// @param to The user whose balance will receive the tokens
function supplyTokenTo(uint256 amount, address to) public override {
sushiAddr.transferFrom(msg.sender, address(this), amount);
sushiAddr.approve(address(sushiBar), amount);
ISushiBar bar = sushiBar;
uint256 beforeBalance = bar.balanceOf(address(this));
bar.enter(amount);
uint256 afterBalance = bar.balanceOf(address(this));
uint256 balanceDiff = afterBalance.sub(beforeBalance);
balances[to] = balances[to].add(balanceDiff);
}
/// @notice Redeems tokens from the yield source to the msg.sender, it burns yield bearing tokens and returns token to the sender.
/// @param amount The amount of `token()` to withdraw. Denominated in `token()` as above.
/// @dev The maxiumum that can be called for token() is calculated by balanceOfToken() above.
/// @return The actual amount of tokens that were redeemed. This may be different from the amount passed due to the fractional math involved.
function redeemToken(uint256 amount) public override returns (uint256) {
ISushiBar bar = sushiBar;
ISushi sushi = sushiAddr;
uint256 totalShares = bar.totalSupply();
if(totalShares == 0) return 0;
uint256 barSushiBalance = sushi.balanceOf(address(bar));
if(barSushiBalance == 0) return 0;
uint256 sushiBeforeBalance = sushi.balanceOf(address(this));
uint256 requiredShares = ((amount.mul(totalShares) + totalShares)).div(barSushiBalance);
if(requiredShares == 0) return 0;
uint256 requiredSharesBalance = requiredShares.sub(1);
bar.leave(requiredSharesBalance);
uint256 sushiAfterBalance = sushi.balanceOf(address(this));
uint256 sushiBalanceDiff = sushiAfterBalance.sub(sushiBeforeBalance);
balances[msg.sender] = balances[msg.sender].sub(requiredSharesBalance);
sushi.transfer(msg.sender, sushiBalanceDiff);
return (sushiBalanceDiff);
}
} | 818 | 94 | 2 | 1. [M-02] Return values of ERC20 transfer and transferFrom are unchecked (Unchecked external calls)
In the contracts BadgerYieldSource and SushiYieldSource, the return values of ERC20 transfer and transferFrom are not checked to be true, which could be false if the transferred tokens are not ERC20-compliant (e.g., BADGER). In that case, the transfer fails without being noticed by the calling contract.
`redeemToken` and `supplyTokenTo` function.
2. [M-03] SafeMath not completely used in yield source contracts. (Overflow)
In `redeemToken` function, ` uint256 requiredShares = ((amount.mul(totalShares) + totalShares)).div(barSushiBalance);` | 2 |
69_NFTXStakingZap.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interface/INFTXVault.sol";
import "./interface/INFTXVaultFactory.sol";
import "./interface/INFTXSimpleFeeDistributor.sol";
import "./interface/INFTXLPStaking.sol";
import "./interface/INFTXInventoryStaking.sol";
import "./interface/ITimelockRewardDistributionToken.sol";
import "./interface/IUniswapV2Router01.sol";
import "./testing/IERC721.sol";
import "./token/IERC1155Upgradeable.sol";
import "./token/IERC20Upgradeable.sol";
import "./token/ERC721HolderUpgradeable.sol";
import "./token/ERC1155HolderUpgradeable.sol";
import "./util/OwnableUpgradeable.sol";
// Authors: @0xKiwi_.
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
contract NFTXStakingZap is Ownable, ReentrancyGuard, ERC721HolderUpgradeable, ERC1155HolderUpgradeable {
IWETH public immutable WETH;
INFTXLPStaking public immutable lpStaking;
INFTXInventoryStaking public immutable inventoryStaking;
INFTXVaultFactory public immutable nftxFactory;
IUniswapV2Router01 public immutable sushiRouter;
uint256 public lpLockTime = 48 hours;
uint256 public inventoryLockTime = 7 days;
uint256 constant BASE = 10**18;
event UserStaked(uint256 vaultId, uint256 count, uint256 lpBalance, uint256 timelockUntil, address sender);
constructor(address _nftxFactory, address _sushiRouter) Ownable() ReentrancyGuard() {
nftxFactory = INFTXVaultFactory(_nftxFactory);
lpStaking = INFTXLPStaking(INFTXSimpleFeeDistributor(INFTXVaultFactory(_nftxFactory).feeDistributor()).lpStaking());
inventoryStaking = INFTXInventoryStaking(INFTXSimpleFeeDistributor(INFTXVaultFactory(_nftxFactory).feeDistributor()).inventoryStaking());
sushiRouter = IUniswapV2Router01(_sushiRouter);
WETH = IWETH(IUniswapV2Router01(_sushiRouter).WETH());
IERC20Upgradeable(address(IUniswapV2Router01(_sushiRouter).WETH())).approve(_sushiRouter, type(uint256).max);
}
function setLPLockTime(uint256 newLPLockTime) external onlyOwner {
require(newLPLockTime <= 7 days, "Lock too long");
lpLockTime = newLPLockTime;
}
function setInventoryLockTime(uint256 newInventoryLockTime) external onlyOwner {
require(newInventoryLockTime <= 14 days, "Lock too long");
inventoryLockTime = newInventoryLockTime;
}
function provideInventory721(uint256 vaultId, uint256[] memory tokenIds) public {
uint256 count = tokenIds.length;
INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId));
uint256 xTokensMinted = inventoryStaking.timelockMintFor(vaultId, count*BASE, msg.sender, inventoryLockTime);
address xToken = inventoryStaking.vaultXToken(vaultId);
uint256 oldBal = IERC20Upgradeable(vault).balanceOf(xToken);
uint256[] memory amounts = new uint256[](0);
address assetAddress = vault.assetAddress();
for (uint256 i = 0; i < tokenIds.length; i++) {
transferFromERC721(assetAddress, tokenIds[i], address(vault));
approveERC721(assetAddress, address(vault), tokenIds[i]);
}
vault.mintTo(tokenIds, amounts, address(xToken));
uint256 newBal = IERC20Upgradeable(vault).balanceOf(xToken);
require(newBal == oldBal + count*BASE, "Incorrect vtokens minted");
}
function provideInventory1155(uint256 vaultId, uint256[] memory tokenIds, uint256[] memory amounts) public {
uint256 count;
for (uint256 i = 0; i < tokenIds.length; i++) {
count += amounts[i];
}
INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId));
uint256 xTokensMinted = inventoryStaking.timelockMintFor(vaultId, count*BASE, msg.sender, inventoryLockTime);
address xToken = inventoryStaking.vaultXToken(vaultId);
uint256 oldBal = IERC20Upgradeable(vault).balanceOf(address(xToken));
IERC1155Upgradeable nft = IERC1155Upgradeable(vault.assetAddress());
nft.safeBatchTransferFrom(msg.sender, address(this), tokenIds, amounts, "");
nft.setApprovalForAll(address(vault), true);
vault.mintTo(tokenIds, amounts, address(xToken));
uint256 newBal = IERC20Upgradeable(vault).balanceOf(address(xToken));
require(newBal == oldBal + count*BASE, "Incorrect vtokens minted");
}
function addLiquidity721ETH(
uint256 vaultId,
uint256[] memory ids,
uint256 minWethIn
) public payable returns (uint256) {
return addLiquidity721ETHTo(vaultId, ids, minWethIn, msg.sender);
}
function addLiquidity721ETHTo(
uint256 vaultId,
uint256[] memory ids,
uint256 minWethIn,
address to
) public payable nonReentrant returns (uint256) {
WETH.deposit{value: msg.value}();
(, uint256 amountEth, uint256 liquidity) = _addLiquidity721WETH(vaultId, ids, minWethIn, msg.value, to);
// Return extras.
if (amountEth < msg.value) {
WETH.withdraw(msg.value-amountEth);
payable(to).call{value: msg.value-amountEth};
}
return liquidity;
}
function addLiquidity1155ETH(
uint256 vaultId,
uint256[] memory ids,
uint256[] memory amounts,
uint256 minEthIn
) public payable returns (uint256) {
return addLiquidity1155ETHTo(vaultId, ids, amounts, minEthIn, msg.sender);
}
function addLiquidity1155ETHTo(
uint256 vaultId,
uint256[] memory ids,
uint256[] memory amounts,
uint256 minEthIn,
address to
) public payable nonReentrant returns (uint256) {
WETH.deposit{value: msg.value}();
// Finish this.
(, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minEthIn, msg.value, to);
// Return extras.
if (amountEth < msg.value) {
WETH.withdraw(msg.value-amountEth);
payable(to).call{value: msg.value-amountEth};
}
return liquidity;
}
function addLiquidity721(
uint256 vaultId,
uint256[] memory ids,
uint256 minWethIn,
uint256 wethIn
) public returns (uint256) {
return addLiquidity721To(vaultId, ids, minWethIn, wethIn, msg.sender);
}
function addLiquidity721To(
uint256 vaultId,
uint256[] memory ids,
uint256 minWethIn,
uint256 wethIn,
address to
) public nonReentrant returns (uint256) {
IERC20Upgradeable(address(WETH)).transferFrom(msg.sender, address(this), wethIn);
(, uint256 amountEth, uint256 liquidity) = _addLiquidity721WETH(vaultId, ids, minWethIn, wethIn, to);
// Return extras.
if (amountEth < wethIn) {
WETH.transfer(to, wethIn-amountEth);
}
return liquidity;
}
function addLiquidity1155(
uint256 vaultId,
uint256[] memory ids,
uint256[] memory amounts,
uint256 minWethIn,
uint256 wethIn
) public returns (uint256) {
return addLiquidity1155To(vaultId, ids, amounts, minWethIn, wethIn, msg.sender);
}
function addLiquidity1155To(
uint256 vaultId,
uint256[] memory ids,
uint256[] memory amounts,
uint256 minWethIn,
uint256 wethIn,
address to
) public nonReentrant returns (uint256) {
IERC20Upgradeable(address(WETH)).transferFrom(msg.sender, address(this), wethIn);
(, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minWethIn, wethIn, to);
// Return extras.
if (amountEth < wethIn) {
WETH.transfer(to, wethIn-amountEth);
}
return liquidity;
}
function _addLiquidity721WETH(
uint256 vaultId,
uint256[] memory ids,
uint256 minWethIn,
uint256 wethIn,
address to
) internal returns (uint256, uint256, uint256) {
address vault = nftxFactory.vault(vaultId);
require(vault != address(0), "NFTXZap: Vault does not exist");
// Transfer tokens to zap and mint to NFTX.
address assetAddress = INFTXVault(vault).assetAddress();
for (uint256 i = 0; i < ids.length; i++) {
transferFromERC721(assetAddress, ids[i], vault);
approveERC721(assetAddress, vault, ids[i]);
}
uint256[] memory emptyIds;
uint256 count = INFTXVault(vault).mint(ids, emptyIds);
uint256 balance = (count * BASE);
// We should not be experiencing fees.
require(balance == IERC20Upgradeable(vault).balanceOf(address(this)), "Did not receive expected balance");
return _addLiquidityAndLock(vaultId, vault, balance, minWethIn, wethIn, to);
}
function _addLiquidity1155WETH(
uint256 vaultId,
uint256[] memory ids,
uint256[] memory amounts,
uint256 minWethIn,
uint256 wethIn,
address to
) internal returns (uint256, uint256, uint256) {
address vault = nftxFactory.vault(vaultId);
require(vault != address(0), "NFTXZap: Vault does not exist");
// Transfer tokens to zap and mint to NFTX.
address assetAddress = INFTXVault(vault).assetAddress();
IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(msg.sender, address(this), ids, amounts, "");
IERC1155Upgradeable(assetAddress).setApprovalForAll(vault, true);
uint256 count = INFTXVault(vault).mint(ids, amounts);
uint256 balance = (count * BASE);
// We should not be experiencing fees.
require(balance == IERC20Upgradeable(vault).balanceOf(address(this)), "Did not receive expected balance");
return _addLiquidityAndLock(vaultId, vault, balance, minWethIn, wethIn, to);
}
function _addLiquidityAndLock(
uint256 vaultId,
address vault,
uint256 minTokenIn,
uint256 minWethIn,
uint256 wethIn,
address to
) internal returns (uint256, uint256, uint256) {
// Provide liquidity.
IERC20Upgradeable(vault).approve(address(sushiRouter), minTokenIn);
(uint256 amountToken, uint256 amountEth, uint256 liquidity) = sushiRouter.addLiquidity(
address(vault),
sushiRouter.WETH(),
minTokenIn,
wethIn,
minTokenIn,
minWethIn,
address(this),
block.timestamp
);
// Stake in LP rewards contract
address lpToken = pairFor(vault, address(WETH));
IERC20Upgradeable(lpToken).approve(address(lpStaking), liquidity);
lpStaking.timelockDepositFor(vaultId, to, liquidity, lpLockTime);
if (amountToken < minTokenIn) {
IERC20Upgradeable(vault).transfer(to, minTokenIn-amountToken);
}
uint256 lockEndTime = block.timestamp + lpLockTime;
emit UserStaked(vaultId, minTokenIn, liquidity, lockEndTime, to);
return (amountToken, amountEth, liquidity);
}
function transferFromERC721(address assetAddr, uint256 tokenId, address to) internal virtual {
address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
bytes memory data;
if (assetAddr == kitties) {
// Cryptokitties.
data = abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), tokenId);
} else if (assetAddr == punks) {
// CryptoPunks.
// Fix here for frontrun attack. Added in v1.0.2.
bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId);
(bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress);
(address owner) = abi.decode(result, (address));
require(checkSuccess && owner == msg.sender, "Not the owner");
data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
} else {
// Default.
// We push to the vault to avoid an unneeded transfer.
data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", msg.sender, to, tokenId);
}
(bool success, bytes memory resultData) = address(assetAddr).call(data);
require(success, string(resultData));
}
function approveERC721(address assetAddr, address to, uint256 tokenId) internal virtual {
address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
bytes memory data;
if (assetAddr == kitties) {
// Cryptokitties.
data = abi.encodeWithSignature("approve(address,uint256)", to, tokenId);
} else if (assetAddr == punks) {
// CryptoPunks.
data = abi.encodeWithSignature("offerPunkForSaleToAddress(uint256,uint256,address)", tokenId, 0, to);
} else {
// No longer needed to approve with pushing.
return;
}
(bool success, bytes memory resultData) = address(assetAddr).call(data);
require(success, string(resultData));
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(uint256(keccak256(abi.encodePacked(
hex'ff',
sushiRouter.factory(),
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303'
// init code hash
)))));
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
receive() external payable {
}
function rescue(address token) external onlyOwner {
IERC20Upgradeable(token).transfer(msg.sender, IERC20Upgradeable(token).balanceOf(address(this)));
}
} | 4,834 | 481 | 4 | 1. [H-03] A vault can be locked from MarketplaceZap and StakingZap
Function `_addLiquidity721WETH` and `_addLiquidity1155WETH`
` require(balance == IERC20Upgradeable(vault).balanceOf(address(this)), "Did not receive expected balance");`
2. [M-01] Missing non reentrancy modifier (Reentrancy)
3. [M-04] NFTXStakingZap and NFTXMarketplaceZap's transferFromERC721 transfer Cryptokitties to the wrong address
`transferFromERC721(address assetAddr, uint256 tokenId, address to)` should transfer from msg.sender to to. It transfers to address(this) instead when ERC721 is Cryptokitties. As there is no additional logic for this case it seems to be a mistake that leads to wrong NFT accounting after such a transfer as NFT will be missed in the vault (which is to).
4. [M-08] Low-level call return value not checked (Unchecked external calls)
The NFTXStakingZap.addLiquidity721ETHTo function performs a low-level .call in payable(to).call{value: msg.value-amountEth} but does not check the return value if the call succeeded.
5. [M-09] Bypass zap timelock (Time control)
The default value of inventoryLockTime in NFTXStakingZap is 7 days while DEFAULT_LOCKTIME in NFTXInventoryStaking is 2 ms. These timelock value are used in NFTXInventoryStaking to eventually call _timelockMint in XTokenUpgradeable.
6. [M-17] transfer return value is ignored (Unchecked external calls)
`addLiquidity721To` and `addLiquidity1155To`, `_addLiquidityAndLock`, `rescue` | 6 |
5_Pools.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
// Interfaces
import "./interfaces/iERC20.sol";
import "./interfaces/iUTILS.sol";
import "./interfaces/iVADER.sol";
import "./interfaces/iFACTORY.sol";
contract Pools {
// Parameters
bool private inited;
uint public pooledVADER;
uint public pooledUSDV;
address public VADER;
address public USDV;
address public ROUTER;
address public FACTORY;
mapping(address => bool) _isMember;
mapping(address => bool) _isAsset;
mapping(address => bool) _isAnchor;
mapping(address => uint) public mapToken_Units;
mapping(address => mapping(address => uint)) public mapTokenMember_Units;
mapping(address => uint) public mapToken_baseAmount;
mapping(address => uint) public mapToken_tokenAmount;
// Events
event AddLiquidity(address indexed member, address indexed base, uint baseAmount, address indexed token, uint tokenAmount, uint liquidityUnits);
event RemoveLiquidity(address indexed member, address indexed base, uint baseAmount, address indexed token, uint tokenAmount, uint liquidityUnits, uint totalUnits);
event Swap(address indexed member, address indexed inputToken, uint inputAmount, address indexed outputToken, uint outputAmount, uint swapFee);
event Sync(address indexed token, address indexed pool, uint addedAmount);
event SynthSync(address indexed token, uint burntSynth, uint deletedUnits);
//=====================================CREATION=========================================//
// Constructor
constructor() {}
// Init
function init(address _vader, address _usdv, address _router, address _factory) public {
require(inited == false);
inited = true;
VADER = _vader;
USDV = _usdv;
ROUTER = _router;
FACTORY = _factory;
}
//====================================LIQUIDITY=========================================//
function addLiquidity(address base, address token, address member) external returns(uint liquidityUnits) {
require(token != USDV && token != VADER);
uint _actualInputBase;
if(base == VADER){
if(!isAnchor(token)){
_isAnchor[token] = true;
}
_actualInputBase = getAddedAmount(VADER, token);
} else if (base == USDV) {
if(!isAsset(token)){
_isAsset[token] = true;
}
_actualInputBase = getAddedAmount(USDV, token);
}
uint _actualInputToken = getAddedAmount(token, token);
liquidityUnits = iUTILS(UTILS()).calcLiquidityUnits(_actualInputBase, mapToken_baseAmount[token], _actualInputToken, mapToken_tokenAmount[token], mapToken_Units[token]);
mapTokenMember_Units[token][member] += liquidityUnits;
mapToken_Units[token] += liquidityUnits;
mapToken_baseAmount[token] += _actualInputBase;
mapToken_tokenAmount[token] += _actualInputToken;
emit AddLiquidity(member, base, _actualInputBase, token, _actualInputToken, liquidityUnits);
}
function removeLiquidity(address base, address token, uint basisPoints) external returns (uint outputBase, uint outputToken) {
return _removeLiquidity(base, token, basisPoints, tx.origin);
}
function removeLiquidityDirectly(address base, address token, uint basisPoints) external returns (uint outputBase, uint outputToken) {
return _removeLiquidity(base, token, basisPoints, msg.sender);
}
function _removeLiquidity(address base, address token, uint basisPoints, address member) internal returns (uint outputBase, uint outputToken) {
require(base == USDV || base == VADER);
uint _units = iUTILS(UTILS()).calcPart(basisPoints, mapTokenMember_Units[token][member]);
outputBase = iUTILS(UTILS()).calcShare(_units, mapToken_Units[token], mapToken_baseAmount[token]);
outputToken = iUTILS(UTILS()).calcShare(_units, mapToken_Units[token], mapToken_tokenAmount[token]);
mapToken_Units[token] -=_units;
mapTokenMember_Units[token][member] -= _units;
mapToken_baseAmount[token] -= outputBase;
mapToken_tokenAmount[token] -= outputToken;
emit RemoveLiquidity(member, base, outputBase, token, outputToken, _units, mapToken_Units[token]);
transferOut(base, outputBase, member);
transferOut(token, outputToken, member);
return (outputBase, outputToken);
}
//=======================================SWAP===========================================//
// Designed to be called by a router, but can be called directly
function swap(address base, address token, address member, bool toBase) external returns (uint outputAmount) {
if(toBase){
uint _actualInput = getAddedAmount(token, token);
outputAmount = iUTILS(UTILS()).calcSwapOutput(_actualInput, mapToken_tokenAmount[token], mapToken_baseAmount[token]);
uint _swapFee = iUTILS(UTILS()).calcSwapFee(_actualInput, mapToken_tokenAmount[token], mapToken_baseAmount[token]);
mapToken_tokenAmount[token] += _actualInput;
mapToken_baseAmount[token] -= outputAmount;
emit Swap(member, token, _actualInput, base, outputAmount, _swapFee);
transferOut(base, outputAmount, member);
} else {
uint _actualInput = getAddedAmount(base, token);
outputAmount = iUTILS(UTILS()).calcSwapOutput(_actualInput, mapToken_baseAmount[token], mapToken_tokenAmount[token]);
uint _swapFee = iUTILS(UTILS()).calcSwapFee(_actualInput, mapToken_baseAmount[token], mapToken_tokenAmount[token]);
mapToken_baseAmount[token] += _actualInput;
mapToken_tokenAmount[token] -= outputAmount;
emit Swap(member, base, _actualInput, token, outputAmount, _swapFee);
transferOut(token, outputAmount, member);
}
}
// Add to balances directly (must send first)
function sync(address token, address pool) external {
uint _actualInput = getAddedAmount(token, pool);
if (token == VADER || token == USDV){
mapToken_baseAmount[pool] += _actualInput;
} else {
mapToken_tokenAmount[pool] += _actualInput;
// } else if(isSynth()){
// //burnSynth && deleteUnits
}
emit Sync(token, pool, _actualInput);
}
//======================================SYNTH=========================================//
// Should be done with intention, is gas-intensive
function deploySynth(address token) external {
require(token != VADER || token != USDV);
iFACTORY(FACTORY).deploySynth(token);
}
// Mint a Synth against its own pool
function mintSynth(address base, address token, address member) external returns (uint outputAmount) {
require(iFACTORY(FACTORY).isSynth(getSynth(token)), "!synth");
uint _actualInputBase = getAddedAmount(base, token);
uint _synthUnits = iUTILS(UTILS()).calcSynthUnits(_actualInputBase, mapToken_baseAmount[token], mapToken_Units[token]);
outputAmount = iUTILS(UTILS()).calcSwapOutput(_actualInputBase, mapToken_baseAmount[token], mapToken_tokenAmount[token]);
mapTokenMember_Units[token][address(this)] += _synthUnits;
mapToken_Units[token] += _synthUnits;
mapToken_baseAmount[token] += _actualInputBase;
emit AddLiquidity(member, base, _actualInputBase, token, 0, _synthUnits);
iFACTORY(FACTORY).mintSynth(getSynth(token), member, outputAmount);
}
// Burn a Synth to get out BASE
function burnSynth(address base, address token, address member) external returns (uint outputBase) {
uint _actualInputSynth = iERC20(getSynth(token)).balanceOf(address(this));
uint _unitsToDelete = iUTILS(UTILS()).calcShare(_actualInputSynth, iERC20(getSynth(token)).totalSupply(), mapTokenMember_Units[token][address(this)]);
iERC20(getSynth(token)).burn(_actualInputSynth);
mapTokenMember_Units[token][address(this)] -= _unitsToDelete;
mapToken_Units[token] -= _unitsToDelete;
outputBase = iUTILS(UTILS()).calcSwapOutput(_actualInputSynth, mapToken_tokenAmount[token], mapToken_baseAmount[token]);
mapToken_baseAmount[token] -= outputBase;
emit RemoveLiquidity(member, base, outputBase, token, 0, _unitsToDelete, mapToken_Units[token]);
transferOut(base, outputBase, member);
}
// Remove a synth, make other LPs richer
function syncSynth(address token) external {
uint _actualInputSynth = iERC20(getSynth(token)).balanceOf(address(this));
uint _unitsToDelete = iUTILS(UTILS()).calcShare(_actualInputSynth, iERC20(getSynth(token)).totalSupply(), mapTokenMember_Units[token][address(this)]);
iERC20(getSynth(token)).burn(_actualInputSynth);
mapTokenMember_Units[token][address(this)] -= _unitsToDelete;
mapToken_Units[token] -= _unitsToDelete;
emit SynthSync(token, _actualInputSynth, _unitsToDelete);
}
//======================================LENDING=========================================//
// Assign units to callee (ie, a LendingRouter)
function lockUnits(uint units, address token, address member) external {
mapTokenMember_Units[token][member] -= units;
mapTokenMember_Units[token][msg.sender] += units;
}
// Assign units to callee (ie, a LendingRouter)
function unlockUnits(uint units, address token, address member) external {
mapTokenMember_Units[token][msg.sender] -= units;
mapTokenMember_Units[token][member] += units;
}
//======================================HELPERS=========================================//
// Safe adds
function getAddedAmount(address _token, address _pool) internal returns(uint addedAmount) {
uint _balance = iERC20(_token).balanceOf(address(this));
if(_token == VADER && _pool != VADER){
addedAmount = _balance - pooledVADER;
pooledVADER = pooledVADER + addedAmount;
} else if(_token == USDV) {
addedAmount = _balance - pooledUSDV;
pooledUSDV = pooledUSDV + addedAmount;
} else {
addedAmount = _balance - mapToken_tokenAmount[_pool];
}
}
function transferOut(address _token, uint _amount, address _recipient) internal {
if(_token == VADER){
pooledVADER = pooledVADER - _amount;
} else if(_token == USDV) {
pooledUSDV = pooledUSDV - _amount;
}
if(_recipient != address(this)){
iERC20(_token).transfer(_recipient, _amount);
}
}
function isMember(address member) public view returns(bool) {
return _isMember[member];
}
function isAsset(address token) public view returns(bool) {
return _isAsset[token];
}
function isAnchor(address token) public view returns(bool) {
return _isAnchor[token];
}
function getPoolAmounts(address token) external view returns(uint, uint) {
return (getBaseAmount(token), getTokenAmount(token));
}
function getBaseAmount(address token) public view returns(uint) {
return mapToken_baseAmount[token];
}
function getTokenAmount(address token) public view returns(uint) {
return mapToken_tokenAmount[token];
}
function getUnits(address token) external view returns(uint) {
return mapToken_Units[token];
}
function getMemberUnits(address token, address member) external view returns(uint) {
return mapTokenMember_Units[token][member];
}
function getSynth(address token) public view returns (address) {
return iFACTORY(FACTORY).getSynth(token);
}
function isSynth(address token) public view returns (bool) {
return iFACTORY(FACTORY).isSynth(token);
}
function UTILS() public view returns(address){
return iVADER(VADER).UTILS();
}
} | 2,783 | 248 | 3 | 1. [H-01] Unhandled return value of transfer in transferOut() of Pools.sol (Unchecked return values)
ERC20 implementations are not always consistent. Some implementations of `transfer` and `transferFrom` could return ‘false’ on failure instead of reverting. It is safer to wrap such calls into require() statements to handle these failures. `transferOut()`
2. [H-11] Swap token can be traded as fake base token
The Pools.swap function does not check if base is one of the base tokens. One can transfer tokens to the pool and set base=token and call swap(token, token, member, toBase=false)
3. [H-13] 4 Synths can be minted with fake base token
The Pools.mintSynth function does not check if base is one of the base tokens. One can transfer tokens to the pool and set base=token and call mintSynth(token, token, member).
4. [H-22] Users may unintentionally remove liquidity under a phishing attack. (Unsafe Tx.origin)
The removeLiquidity function in Pools.sol uses tx.origin to determine the person who wants to remove liquidity. However, such a design is dangerous since the pool assumes that this function is called from the router, which may not be true if the user is under a phishing attack, and he could unintentionally remove liquidity.
5. [M-01] User may not get IL protection if certain functions are called directly in Pools.sol
Functions removeLiquidity() and removeLiquidityDirectly() when called directly, do not provide the the user with IL protection unlike when calling the corresponding removeLiquidity() function in Router.sol
6. [M-10] Incorrect operator used in deploySynth() of Pools.sol
7. [M-13] Init function can be called by everyone (Access control)
8. [M-14] Pool functions can be called before initialization in _init_() of Pools.sol (initial) | 8 |
6_Beebots.sol | pragma solidity 0.7.6;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
interface BetaToken {
function tokenOwner(uint index) external view returns(address);
}
interface ERC721TokenReceiver
{
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Beebots is IERC721 {
using SafeMath for uint256;
/**
* Event emitted when minting a new NFT. "createdVia" is the index of the alhpa/beta token that was used to mint, or 0 if not applicable.
*/
event Mint(uint indexed index, address indexed minter, uint createdVia);
/**
* Event emitted when a trade is executed.
*/
event Trade(bytes32 indexed hash, address indexed maker, address taker, uint makerWei, uint[] makerIds, uint takerWei, uint[] takerIds);
/**
* Event emitted when ETH is deposited into the contract.
*/
event Deposit(address indexed account, uint amount);
/**
* Event emitted when ETH is withdrawn from the contract.
*/
event Withdraw(address indexed account, uint amount);
/**
* Event emitted when a trade offer is cancelled.
*/
event OfferCancelled(bytes32 hash);
/**
* Event emitted when the public sale begins.
*/
event SaleBegins();
/**
* Event emitted when the community grant period ends.
*/
event CommunityGrantEnds();
bytes4 internal constant MAGIC_ERC721_RECEIVED = 0x150b7a02;
// Hash to the NFT content
string public contentHash = "todo";
uint public constant TOKEN_LIMIT = 30;
uint public constant SALE_LIMIT = 20;
mapping (uint => address) private idToCreator;
mapping(bytes4 => bool) internal supportedInterfaces;
mapping (uint256 => address) internal idToOwner;
mapping (uint256 => uint256) public idToCreatorNft;
mapping (uint256 => uint256) public creatorNftMints;
mapping (uint256 => address) internal idToApproval;
mapping (address => mapping (address => bool)) internal ownerToOperators;
mapping(address => uint256[]) internal ownerToIds;
mapping(uint256 => uint256) internal idToOwnerIndex;
string internal nftName = "Beebots";
string internal nftSymbol = unicode"🐝";
uint internal numTokens = 0;
uint internal numSales = 0;
address internal beta;
address internal alpha;
address payable internal deployer;
address payable internal beneficiary;
bool public communityGrant = true;
bool public publicSale = false;
uint private price;
uint public saleStartTime;
uint public saleDuration;
//// Random index assignment
uint internal nonce = 0;
uint[TOKEN_LIMIT] internal indices;
//// Market
bool public marketPaused;
bool public contractSealed;
mapping (address => uint256) public ethBalance;
mapping (bytes32 => bool) public cancelledOffers;
modifier onlyDeployer() {
require(msg.sender == deployer, "Only deployer.");
_;
}
bool private reentrancyLock = false;
/* Prevent a contract function from being reentrant-called. */
modifier reentrancyGuard {
if (reentrancyLock) {
revert();
}
reentrancyLock = true;
_;
reentrancyLock = false;
}
modifier canOperate(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], "Cannot operate.");
_;
}
modifier canTransfer(uint256 _tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| idToApproval[_tokenId] == msg.sender
|| ownerToOperators[tokenOwner][msg.sender], "Cannot transfer."
);
_;
}
modifier validNFToken(uint256 _tokenId) {
require(idToOwner[_tokenId] != address(0), "Invalid token.");
_;
}
constructor(address _beta, address _alpha, address payable _beneficiary) {
supportedInterfaces[0x01ffc9a7] = true;
supportedInterfaces[0x80ac58cd] = true;
supportedInterfaces[0x780e9d63] = true;
supportedInterfaces[0x5b5e139f] = true;
deployer = msg.sender;
beta = _beta;
alpha = _alpha;
beneficiary = _beneficiary;
}
function startSale(uint _price, uint _saleDuration) external onlyDeployer {
require(!publicSale, "Sale already started.");
price = _price;
saleDuration = _saleDuration;
saleStartTime = block.timestamp;
publicSale = true;
emit SaleBegins();
}
function endCommunityGrant() external onlyDeployer {
require(communityGrant, "Grant period already ended.");
communityGrant = false;
emit CommunityGrantEnds();
}
function pauseMarket(bool _paused) external onlyDeployer {
require(!contractSealed, "Contract sealed.");
marketPaused = _paused;
}
function sealContract() external onlyDeployer {
contractSealed = true;
}
//////////////////////////
//// ERC 721 and 165 ////
//////////////////////////
function isContract(address _addr) internal view returns (bool addressCheck) {
uint256 size;
assembly { size := extcodesize(_addr) }
addressCheck = size > 0;
}
function supportsInterface(bytes4 _interfaceID) external view override returns (bool) {
return supportedInterfaces[_interfaceID];
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) external override {
_safeTransferFrom(_from, _to, _tokenId, _data);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
_safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom(address _from, address _to, uint256 _tokenId) external override canTransfer(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Wrong from address.");
require(_to != address(0), "Cannot send to 0x0.");
_transfer(_to, _tokenId);
}
function approve(address _approved, uint256 _tokenId) external override canOperate(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
function setApprovalForAll(address _operator, bool _approved) external override {
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function balanceOf(address _owner) external view override returns (uint256) {
require(_owner != address(0));
return _getOwnerNFTCount(_owner);
}
function ownerOf(uint256 _tokenId) external view override returns (address _owner) {
_owner = idToOwner[_tokenId];
}
function getApproved(uint256 _tokenId) external view override validNFToken(_tokenId) returns (address) {
return idToApproval[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external override view returns (bool) {
return ownerToOperators[_owner][_operator];
}
function _transfer(address _to, uint256 _tokenId) internal {
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
function randomIndex() internal returns (uint) {
uint totalSize = TOKEN_LIMIT - numTokens;
uint index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
uint value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
// Move last value to selected position
if (indices[totalSize - 1] == 0) {
// Array position not initialized, so use position
indices[index] = totalSize - 1;
} else {
// Array position holds a value so use that
indices[index] = indices[totalSize - 1];
}
nonce.add(1);
// Don't allow a zero index, start counting at 1
return value.add(1);
}
// Calculate the mint price
function getPrice() public view returns (uint) {
require(publicSale, "Sale not started.");
uint elapsed = block.timestamp.sub(saleStartTime);
if (elapsed > saleDuration) {
return 0;
} else {
return saleDuration.sub(elapsed).mul(price).div(saleDuration);
}
}
// The deployer can mint in bulk without paying
function devMint(uint quantity, address recipient) external onlyDeployer {
for (uint i = 0; i < quantity; i++) {
_mint(recipient, 0);
}
}
function mintsRemaining() external view returns (uint) {
return SALE_LIMIT.sub(numSales);
}
/**
* Community grant minting.
*/
function mintWithAlphaOrBeta(uint _createVia) external reentrancyGuard returns (uint) {
require(communityGrant);
require(_createVia > 0 && _createVia <= 600, "Invalid alpha/beta index.");
require(creatorNftMints[_createVia] == 0, "Already minted with this alpha/beta");
if (_createVia > 400) {
// It's an alpha
// Compute the alpha ID
uint alphaId = _createVia.sub(400);
// Make sure the sender owns the alpha
require(IERC721(alpha).ownerOf(alphaId) == msg.sender, "Not the owner of this alpha.");
} else {
// It's a beta
// Compute the beta ID, 0-based
uint betaId = _createVia.sub(1);
// Make sure the sender owns the beta
require(BetaToken(beta).tokenOwner(betaId) == msg.sender, "Not the owner of this beta.");
}
creatorNftMints[_createVia]++;
return _mint(msg.sender, _createVia);
}
/**
* Public sale minting.
*/
function mint() external payable reentrancyGuard returns (uint) {
require(publicSale, "Sale not started.");
require(numSales < SALE_LIMIT, "Sale limit reached.");
uint salePrice = getPrice();
require(msg.value >= salePrice, "Insufficient funds to purchase.");
if (msg.value > salePrice) {
msg.sender.transfer(msg.value.sub(salePrice));
}
beneficiary.transfer(salePrice);
numSales++;
return _mint(msg.sender, 0);
}
function _mint(address _to, uint createdVia) internal returns (uint) {
require(_to != address(0), "Cannot mint to 0x0.");
require(numTokens < TOKEN_LIMIT, "Token limit reached.");
uint id = randomIndex();
idToCreator[id] = _to;
idToCreatorNft[id] = createdVia;
numTokens = numTokens + 1;
_addNFToken(_to, id);
emit Mint(id, _to, createdVia);
emit Transfer(address(0), _to, id);
return id;
}
function _addNFToken(address _to, uint256 _tokenId) internal {
require(idToOwner[_tokenId] == address(0), "Cannot add, already owned.");
idToOwner[_tokenId] = _to;
ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = ownerToIds[_to].length.sub(1);
}
function _removeNFToken(address _from, uint256 _tokenId) internal {
require(idToOwner[_tokenId] == _from, "Incorrect owner.");
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length.sub(1);
if (lastTokenIndex != tokenToRemoveIndex) {
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
function _getOwnerNFTCount(address _owner) internal view returns (uint256) {
return ownerToIds[_owner].length;
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) private canTransfer(_tokenId) validNFToken(_tokenId) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, "Incorrect owner.");
require(_to != address(0));
_transfer(_to, _tokenId);
if (isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ERC721_RECEIVED);
}
}
function _clearApproval(uint256 _tokenId) private {
if (idToApproval[_tokenId] != address(0)) {
delete idToApproval[_tokenId];
}
}
//// Enumerable
function totalSupply() public view returns (uint256) {
return numTokens;
}
function tokenByIndex(uint256 index) public pure returns (uint256) {
require(index > 0 && index < TOKEN_LIMIT);
return index;
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_index < ownerToIds[_owner].length);
return ownerToIds[_owner][_index];
}
//// Metadata
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
/**
* @dev Returns a descriptive name for a collection of NFTokens.
* @return _name Representing name.
*/
function name() external view returns (string memory _name) {
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTokens.
* @return _symbol Representing symbol.
*/
function symbol() external view returns (string memory _symbol) {
_symbol = nftSymbol;
}
/**
* @dev A distinct URI (RFC 3986) for a given NFT.
* @param _tokenId Id for which we want uri.
* @return _tokenId URI of _tokenId.
*/
function tokenURI(uint256 _tokenId) external view validNFToken(_tokenId) returns (string memory) {
return string(abi.encodePacked("https://todo/", toString(_tokenId)));
}
//// MARKET
struct Offer {
address maker;
address taker;
uint256 makerWei;
uint256[] makerIds;
uint256 takerWei;
uint256[] takerIds;
uint256 expiry;
uint256 salt;
}
function hashOffer(Offer memory offer) private pure returns (bytes32){
return keccak256(abi.encode(
offer.maker,
offer.taker,
offer.makerWei,
keccak256(abi.encodePacked(offer.makerIds)),
offer.takerWei,
keccak256(abi.encodePacked(offer.takerIds)),
offer.expiry,
offer.salt
));
}
function hashToSign(address maker, address taker, uint256 makerWei, uint256[] memory makerIds, uint256 takerWei, uint256[] memory takerIds, uint256 expiry, uint256 salt) public pure returns (bytes32) {
Offer memory offer = Offer(maker, taker, makerWei, makerIds, takerWei, takerIds, expiry, salt);
return hashOffer(offer);
}
function hashToVerify(Offer memory offer) private pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOffer(offer)));
}
function verify(address signer, bytes32 hash, bytes memory signature) internal pure returns (bool) {
require(signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28);
return signer == ecrecover(hash, v, r, s);
}
function tradeValid(address maker, address taker, uint256 makerWei, uint256[] memory makerIds, uint256 takerWei, uint256[] memory takerIds, uint256 expiry, uint256 salt, bytes memory signature) view public returns (bool) {
Offer memory offer = Offer(maker, taker, makerWei, makerIds, takerWei, takerIds, expiry, salt);
// Check for cancellation
bytes32 hash = hashOffer(offer);
require(cancelledOffers[hash] == false, "Trade offer was cancelled.");
// Verify signature
bytes32 verifyHash = hashToVerify(offer);
require(verify(offer.maker, verifyHash, signature), "Signature not valid.");
// Check for expiry
require(block.timestamp < offer.expiry, "Trade offer expired.");
// Only one side should ever have to pay, not both
require(makerWei == 0 || takerWei == 0, "Only one side of trade must pay.");
// At least one side should offer tokens
require(makerIds.length > 0 || takerIds.length > 0, "One side must offer tokens.");
// Make sure the maker has funded the trade
require(ethBalance[offer.maker] >= offer.makerWei, "Maker does not have sufficient balance.");
// Ensure the maker owns the maker tokens
for (uint i = 0; i < offer.makerIds.length; i++) {
require(idToOwner[offer.makerIds[i]] == offer.maker, "At least one maker token doesn't belong to maker.");
}
// If the taker can be anybody, then there can be no taker tokens
if (offer.taker == address(0)) {
// If taker not specified, then can't specify IDs
require(offer.takerIds.length == 0, "If trade is offered to anybody, cannot specify tokens from taker.");
} else {
// Ensure the taker owns the taker tokens
for (uint i = 0; i < offer.takerIds.length; i++) {
require(idToOwner[offer.takerIds[i]] == offer.taker, "At least one taker token doesn't belong to taker.");
}
}
return true;
}
function cancelOffer(address maker, address taker, uint256 makerWei, uint256[] memory makerIds, uint256 takerWei, uint256[] memory takerIds, uint256 expiry, uint256 salt) external {
require(maker == msg.sender, "Only the maker can cancel this offer.");
Offer memory offer = Offer(maker, taker, makerWei, makerIds, takerWei, takerIds, expiry, salt);
bytes32 hash = hashOffer(offer);
cancelledOffers[hash] = true;
emit OfferCancelled(hash);
}
function acceptTrade(address maker, address taker, uint256 makerWei, uint256[] memory makerIds, uint256 takerWei, uint256[] memory takerIds, uint256 expiry, uint256 salt, bytes memory signature) external payable reentrancyGuard {
require(!marketPaused, "Market is paused.");
require(msg.sender != maker, "Can't accept ones own trade.");
Offer memory offer = Offer(maker, taker, makerWei, makerIds, takerWei, takerIds, expiry, salt);
ethBalance[msg.sender] += msg.value;
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
require(offer.taker == address(0) || offer.taker == msg.sender, "Not the recipient of this offer.");
require(tradeValid(maker, taker, makerWei, makerIds, takerWei, takerIds, expiry, salt, signature), "Trade not valid.");
require(ethBalance[msg.sender] >= offer.takerWei, "Insufficient funds to execute trade.");
// Transfer ETH
ethBalance[offer.maker] = ethBalance[offer.maker].sub(offer.makerWei);
ethBalance[msg.sender] = ethBalance[msg.sender].add(offer.makerWei);
ethBalance[msg.sender] = ethBalance[msg.sender].sub(offer.takerWei);
ethBalance[offer.maker] = ethBalance[offer.maker].add(offer.takerWei);
// Transfer maker ids to taker (msg.sender)
for (uint i = 0; i < makerIds.length; i++) {
_transfer(msg.sender, makerIds[i]);
}
// Transfer taker ids to maker
for (uint i = 0; i < takerIds.length; i++) {
_transfer(maker, takerIds[i]);
}
// Prevent a replay attack on this offer
bytes32 hash = hashOffer(offer);
cancelledOffers[hash] = true;
emit Trade(hash, offer.maker, msg.sender, offer.makerWei, offer.makerIds, offer.takerWei, offer.takerIds);
}
function withdraw(uint amount) external {
require(amount <= ethBalance[msg.sender]);
ethBalance[msg.sender] = ethBalance[msg.sender].sub(amount);
msg.sender.transfer(amount);
emit Withdraw(msg.sender, amount);
}
function deposit() external payable {
ethBalance[msg.sender] = ethBalance[msg.sender].add(msg.value);
emit Deposit(msg.sender, msg.value);
}
} | 5,567 | 662 | 0 | 1. H-03: Beebots.TradeValid() Will Erroneously Return True When Maker Is Set To Address(0) and makerIds Are Set To The TokenIds of Unminted Beebot NFTs (Lack of input valiadation)
when TradeValid() function, when input `maker` is address(0) | 1 |
12_AccessControl.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes4` identifier. These are expected to be the
* signatures for all the functions in the contract. Special roles should be exposed
* in the external API and be unique:
*
* ```
* bytes4 public constant ROOT = 0x00000000;
* ```
*
* Roles represent restricted access to a function call. For that purpose, use {auth}:
*
* ```
* function foo() public auth {
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `ROOT`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {setRoleAdmin}.
*
* WARNING: The `ROOT` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
contract AccessControl {
struct RoleData {
mapping (address => bool) members;
bytes4 adminRole;
}
mapping (bytes4 => RoleData) private _roles;
bytes4 public constant ROOT = 0x00000000;
bytes4 public constant LOCK = 0xFFFFFFFF;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role
*
* `ROOT` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call.
*/
event RoleGranted(bytes4 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes4 indexed role, address indexed account, address indexed sender);
/**
* @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members.
* Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore.
*/
constructor () {
_grantRole(ROOT, msg.sender);
// Grant ROOT to msg.sender
_setRoleAdmin(LOCK, LOCK);
// Create the LOCK role by setting itself as its own admin, creating an independent role tree
}
/**
* @dev Each function in the contract has its own role, identified by their msg.sig signature.
* ROOT can give and remove access to each function, lock any further access being granted to
* a specific action, or even create other roles to delegate admin control over a function.
*/
modifier auth() {
require (_hasRole(msg.sig, msg.sender), "Access denied");
_;
}
/**
* @dev Allow only if the caller has been granted the admin role of `role`.
*/
modifier admin(bytes4 role) {
require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin");
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes4 role, address account) external view returns (bool) {
return _hasRole(role, account);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes4 role) external view returns (bytes4) {
return _getRoleAdmin(role);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
* If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) {
_setRoleAdmin(role, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes4 role, address account) external virtual admin(role) {
_grantRole(role, account);
}
/**
* @dev Grants all of `role` in `roles` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function grantRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_grantRole(roles[i], account);
}
}
/**
* @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``.
* Emits a {RoleAdminChanged} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function lockRole(bytes4 role) external virtual admin(role) {
_setRoleAdmin(role, LOCK);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes4 role, address account) external virtual admin(role) {
_revokeRole(role, account);
}
/**
* @dev Revokes all of `role` in `roles` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - For each `role` in `roles`, the caller must have ``role``'s admin role.
*/
function revokeRoles(bytes4[] memory roles, address account) external virtual {
for (uint256 i = 0; i < roles.length; i++) {
require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin");
_revokeRole(roles[i], account);
}
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes4 role, address account) external virtual {
require(account == msg.sender, "Renounce only for self");
_revokeRole(role, account);
}
function _hasRole(bytes4 role, address account) internal view returns (bool) {
return _roles[role].members[account];
}
function _getRoleAdmin(bytes4 role) internal view returns (bytes4) {
return _roles[role].adminRole;
}
function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual {
if (_getRoleAdmin(role) != adminRole) {
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, adminRole);
}
}
function _grantRole(bytes4 role, address account) internal {
if (!_hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes4 role, address account) internal {
if (_hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
} | 2,019 | 257 | 0 | 1. [H-02] auth collision possible (Auth issue)
The `auth` mechanism of AccessControl.sol uses function selectors (msg.sig) as a (unique) role definition. Also the _moduleCall allows the code to be extended.
2. [M-09] auth only works well with external functions (Unused modifiers, Insufficient Access Control)
The `auth` modifier of AccessControl.sol doesn't work as you would expect. It checks if you are authorized for msg.sig. However, msg.sig is the signature of the first function you have called (not the current function). So, if you call function A, which calls function B, the "auth" modifier of function B checks if you are authorized for function A! | 2 |
78_FlanBackstop.sol | // SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./facades/FlanLike.sol";
import "./facades/PyroTokenLike.sol";
import "./DAO/Governable.sol";
import "./ERC677/ERC20Burnable.sol";
import "./facades/UniPairLike.sol";
import "hardhat/console.sol";
///@title FlanBackstop (placeholder name)
///@author Justin Goro
/**
* @notice Initially Flan's liquidity may be fairly low, limiting Limbo's ability to reward souls. Flan backstop accepts stablecoins in return for minting Pyroflan.
*Under the hood a smaller quantity of Flan is minted and paired with the stablecoin in Uniswap in order to tilt the price of Flan higher while incresaing liquidity.
* The same operation is performed with PyroFlan
* The calling user then receives PyroFlan equal in value to the intial amount sent in but at the new price. A small premium is added.
* The incentives facing the user: mint $X of PyroFlan with <$X of stablecoin, stake PyroFlan in Limbo for high APY, do not immediately dump because PyroFlan increases in value and because of 2% exit fee.
* The incentives should be enough to encourage a gradual increase in pooled Flan and stablecoins, creating some minting runway for Limbo to accelerate.
* In the future when Flan and Limbo are thriving and Flan is listed on Curve, we can create a version of this for Curve and Uniswap V3 in order to concentrate Flan liquidity and further cement stablecoin status.
* Note: in this version, LP tokens generated are cast into the void. The argument of keeping them for fee revenue is negated by the impact on Flan. It would just be taking from Peter to give to Paul.
*/
///@dev This contract uses Pyrotokens3. At the time of authoring, Pyrotokens3 implementation is incomplete and not fully tested but the interface (ABI) is locked.
contract FlanBackstop is Governable {
/**
*@param dao LimboDAO
*@param flan Flan address
*@param pyroFlan PyroFlan address
*/
constructor(
address dao,
address flan,
address pyroFlan
) Governable(dao) {
config.pyroFlan = pyroFlan;
config.flan = flan;
IERC20(flan).approve(pyroFlan, 2**256 - 1);
}
struct ConfigVars {
address flan;
address pyroFlan;
mapping(address => address) flanLPs;
mapping(address => address) pyroFlanLPs;
mapping(address => uint256) acceptableHighestPrice;
//Highest tolerated Flan per stable
mapping(address => uint8) decimalPlaces;
//USDC and USDT have 6 decimal places because large stablecoin transfers are exactly where you'd like to find accidental bugs
}
ConfigVars public config;
/**
*@param stablecoin One of the popular stablecoins such as USDC, USDT, MIM, OUSD etc.
*@param flanLP Uniswap V2 (or a fork such as Sushi) flan/Stablecoin LP
*@param pyroFlanLP Uniswap V2 (or a fork such as Sushi) pyroFlan/Stablecoin LP
*@param acceptableHighestPrice Since the prices are being read from balances, not oracles, the opportunity for price manipulation through flash loans exists. The community can put a circuit breaker in place to prevent such an exploit.
*@param decimalPlaces USDT and USDC do not conform to common ERC20 practice.
*/
function setBacker(
address stablecoin,
address flanLP,
address pyroFlanLP,
uint256 acceptableHighestPrice,
uint8 decimalPlaces
) external onlySuccessfulProposal {
config.flanLPs[stablecoin] = flanLP;
config.pyroFlanLPs[stablecoin] = pyroFlanLP;
config.acceptableHighestPrice[stablecoin] = acceptableHighestPrice;
config.decimalPlaces[stablecoin] = decimalPlaces;
}
/**
*@notice takes in a stablecoin, mints flan and pyroFlan and pairs with stablecoin in a Uniswap Pair to generate liquidity
*@param stablecoin Stablecoin with which to purchase
*@param amount amount in stablecoin wei units.
*/
function purchasePyroFlan(address stablecoin, uint256 amount) external {
uint normalizedAmount = normalize(stablecoin, amount);
address flanLP = config.flanLPs[stablecoin];
address pyroFlanLP = config.pyroFlanLPs[stablecoin];
require(flanLP != address(0) && pyroFlanLP != address(0), "BACKSTOP: configure stablecoin");
uint256 balanceOfFlanBefore = IERC20(config.flan).balanceOf(flanLP);
uint256 balanceOfStableBefore = IERC20(stablecoin).balanceOf(flanLP);
uint256 priceBefore = (balanceOfFlanBefore * getMagnitude(stablecoin)) / balanceOfStableBefore;
//Price tilt pairs and mint liquidity
FlanLike(config.flan).mint(address(this), normalizedAmount / 2);
IERC20(config.flan).transfer(flanLP, normalizedAmount / 4);
IERC20(stablecoin).transferFrom(msg.sender, flanLP, amount / 2);
UniPairLike(flanLP).mint(address(this));
uint256 redeemRate = PyroTokenLike(config.pyroFlan).redeemRate();
PyroTokenLike(config.pyroFlan).mint(pyroFlanLP, normalizedAmount / 4);
redeemRate = PyroTokenLike(config.pyroFlan).redeemRate();
redeemRate = PyroTokenLike(config.pyroFlan).redeemRate();
IERC20(stablecoin).transferFrom(msg.sender, pyroFlanLP, amount / 2);
UniPairLike(pyroFlanLP).mint(address(this));
uint256 balanceOfFlan = IERC20(config.flan).balanceOf(flanLP);
uint256 balanceOfStable = IERC20(stablecoin).balanceOf(flanLP);
uint256 tiltedPrice = (balanceOfFlan * getMagnitude(stablecoin)) / balanceOfStable;
require(tiltedPrice < config.acceptableHighestPrice[stablecoin], "BACKSTOP: potential price manipulation");
uint256 growth = ((priceBefore - tiltedPrice) * 100) / priceBefore;
uint256 flanToMint = (tiltedPrice * normalizedAmount) / (1 ether);
//share some price tilting with the user to incentivize minting: The larger the purchase, the better the return
uint256 premium = (flanToMint * (growth / 2)) / 100;
FlanLike(config.flan).mint(address(this), flanToMint + premium);
redeemRate = PyroTokenLike(config.pyroFlan).redeemRate();
PyroTokenLike(config.pyroFlan).mint(msg.sender, flanToMint + premium);
redeemRate = PyroTokenLike(config.pyroFlan).redeemRate();
}
function getMagnitude(address token) internal view returns (uint256) {
uint256 places = config.decimalPlaces[token];
return 10**places;
}
function normalize(address token, uint256 amount) internal view returns (uint256) {
uint256 places = config.decimalPlaces[token];
uint256 bump = 10**(18 - places);
return amount * bump;
}
} | 1,684 | 129 | 0 | 1. H-05: Flash loan price manipulation in `purchasePyroFlan()`. L54
The comment on line 54 of FlanBackstop.sol states "the opportunity for price manipulation through flash loans exists", and I agree that this is a serious risk. | 1 |
123_ConvexMasterChef.sol | // SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-0.6/math/SafeMath.sol";
import "@openzeppelin/contracts-0.6/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-0.6/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-0.6/utils/Context.sol";
import "@openzeppelin/contracts-0.6/access/Ownable.sol";
import "./interfaces/IRewarder.sol";
/**
* @title ConvexMasterChef
* @author ConvexFinance
* @notice Masterchef can distribute rewards to n pools over x time
* @dev There are some caveats with this usage - once it's turned on it can't be turned off,
* and thus it can over complicate the distribution of these rewards.
* To kick things off, just transfer CVX here and add some pools - rewards will be distributed
* pro-rata based on the allocation points in each pool vs the total alloc.
*/
contract ConvexMasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount;
// How many LP tokens the user has provided.
uint256 rewardDebt;
// Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CVXs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCvxPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCvxPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken;
// Address of LP token contract.
uint256 allocPoint;
// How many allocation points assigned to this pool. CVX to distribute per block.
uint256 lastRewardBlock;
// Last block number that CVXs distribution occurs.
uint256 accCvxPerShare;
// Accumulated CVXs per share, times 1e12. See below.
IRewarder rewarder;
}
//cvx
IERC20 public immutable cvx;
// CVX tokens created per block.
uint256 public immutable rewardPerBlock;
// Bonus muliplier for early cvx makers.
uint256 public constant BONUS_MULTIPLIER = 2;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CVX mining starts.
uint256 public immutable startBlock;
uint256 public immutable endBlock;
// Events
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event RewardPaid(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
IERC20 _cvx,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _endBlock
) public {
cvx = _cvx;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
endBlock = _endBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
IRewarder _rewarder,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCvxPerShare: 0,
rewarder: _rewarder
})
);
}
// Update the given pool's CVX allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool _withUpdate,
bool _updateRewarder
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
if(_updateRewarder){
poolInfo[_pid].rewarder = _rewarder;
}
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
uint256 clampedTo = _to > endBlock ? endBlock : _to;
uint256 clampedFrom = _from > endBlock ? endBlock : _from;
return clampedTo.sub(clampedFrom);
}
// View function to see pending CVXs on frontend.
function pendingCvx(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCvxPerShare = pool.accCvxPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 cvxReward = multiplier
.mul(rewardPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accCvxPerShare = accCvxPerShare.add(
cvxReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accCvxPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cvxReward = multiplier
.mul(rewardPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
//cvx.mint(address(this), cvxReward);
pool.accCvxPerShare = pool.accCvxPerShare.add(
cvxReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for CVX allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accCvxPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeRewardTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCvxPerShare).div(1e12);
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, msg.sender, msg.sender, 0, user.amount);
}
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCvxPerShare).div(1e12).sub(
user.rewardDebt
);
safeRewardTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accCvxPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, msg.sender, msg.sender, pending, user.amount);
}
emit RewardPaid(msg.sender, _pid, pending);
emit Withdraw(msg.sender, _pid, _amount);
}
function claim(uint256 _pid, address _account) external{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_account];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCvxPerShare).div(1e12).sub(
user.rewardDebt
);
safeRewardTransfer(_account, pending);
user.rewardDebt = user.amount.mul(pool.accCvxPerShare).div(1e12);
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, _account, _account, pending, user.amount);
}
emit RewardPaid(_account, _pid, pending);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, msg.sender, msg.sender, 0, 0);
}
}
// Safe cvx transfer function, just in case if rounding error causes pool to not have enough CVXs.
function safeRewardTransfer(address _to, uint256 _amount) internal {
uint256 cvxBal = cvx.balanceOf(address(this));
if (_amount > cvxBal) {
cvx.safeTransfer(_to, cvxBal);
} else {
cvx.safeTransfer(_to, _amount);
}
}
} | 2,679 | 314 | 2 | 1. M-13: ConvexMasterChef: When `_lpToken` is cvx, reward calculation is incorrect (Reward calculation)
2. M-15: ConvexMasterChef: `safeRewardTransfer` can cause loss of funds (Fund Loss)
All calculations are rounded down, since a lack of tokens in the contracts cannot be rounding errors' fault. So the function is redundant.
3. M-17: ConvexMasterChef's `deposit` and `withdraw` can be reentered drawing all reward funds from the contract if reward token allows for transfer flow control
(reentrancy)
4. M-20: `massUpdatePools()` is susceptible to DoS with block gas limit. (Gas limit)
5. M-21: ConvexMasterChef: When using `add()` and `set()`, it should always call `massUpdatePools()` to update all pools. L96
6. M-22: Duplicate LP token could lead to incorrect reward distribution. `add` L96 (Duplicate LP token) | 6 |
71_Vault.sol | pragma solidity 0.8.7;
/**
* @author InsureDAO
* @title InsureDAO vault contract
* @notice
* SPDX-License-Identifier: GPL-3.0
*/
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IOwnership.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IController.sol";
import "./interfaces/IRegistry.sol";
contract Vault is IVault {
using SafeERC20 for IERC20;
/**
* Storage
*/
address public override token;
IController public controller;
IRegistry public registry;
IOwnership public ownership;
mapping(address => uint256) public override debts;
mapping(address => uint256) public attributions;
uint256 public totalAttributions;
address public keeper;
//keeper can operate utilize(), if address zero, anyone can operate.
uint256 public balance;
//balance of underlying token
uint256 public totalDebt;
//total debt balance. 1debt:1token
uint256 public constant MAGIC_SCALE_1E6 = 1e6;
//internal multiplication scale 1e6 to reduce decimal truncation
event ControllerSet(address controller);
modifier onlyOwner() {
require(
ownership.owner() == msg.sender,
"Restricted: caller is not allowed to operate"
);
_;
}
modifier onlyMarket() {
require(
IRegistry(registry).isListed(msg.sender),
"ERROR_ONLY_MARKET"
);
_;
}
constructor(
address _token,
address _registry,
address _controller,
address _ownership
) {
require(_token != address(0));
require(_registry != address(0));
require(_ownership != address(0));
//controller can be zero
token = _token;
registry = IRegistry(_registry);
controller = IController(_controller);
ownership = IOwnership(_ownership);
}
/**
* Vault Functions
*/
/**
* @notice A market contract can deposit collateral and get attribution point in return
* @param _amount amount of tokens to deposit
* @param _from sender's address
* @param _beneficiaries beneficiary's address array
* @param _shares funds share within beneficiaries (100% = 1e6)
* @return _allocations attribution amount generated from the transaction
*/
function addValueBatch(
uint256 _amount,
address _from,
address[2] memory _beneficiaries,
uint256[2] memory _shares
) external override onlyMarket returns (uint256[2] memory _allocations) {
require(_shares[0] + _shares[1] == 1000000, "ERROR_INCORRECT_SHARE");
uint256 _attributions;
if (totalAttributions == 0) {
_attributions = _amount;
} else {
uint256 _pool = valueAll();
_attributions = (_amount * totalAttributions) / _pool;
}
IERC20(token).safeTransferFrom(_from, address(this), _amount);
balance += _amount;
totalAttributions += _attributions;
for (uint128 i = 0; i < 2; i++) {
uint256 _allocation = (_shares[i] * _attributions) / MAGIC_SCALE_1E6;
attributions[_beneficiaries[i]] += _allocation;
_allocations[i] = _allocation;
}
}
/**
* @notice A market contract can deposit collateral and get attribution point in return
* @param _amount amount of tokens to deposit
* @param _from sender's address
* @param _beneficiary beneficiary's address
* @return _attributions attribution amount generated from the transaction
*/
function addValue(
uint256 _amount,
address _from,
address _beneficiary
) external override onlyMarket returns (uint256 _attributions) {
if (totalAttributions == 0) {
_attributions = _amount;
} else {
uint256 _pool = valueAll();
_attributions = (_amount * totalAttributions) / _pool;
}
IERC20(token).safeTransferFrom(_from, address(this), _amount);
balance += _amount;
totalAttributions += _attributions;
attributions[_beneficiary] += _attributions;
}
/**
* @notice an address that has balance in the vault can withdraw underlying value
* @param _amount amount of tokens to withdraw
* @param _to address to get underlying tokens
* @return _attributions amount of attributions burnet
*/
function withdrawValue(uint256 _amount, address _to)
external
override
returns (uint256 _attributions)
{
require(
attributions[msg.sender] > 0 &&
underlyingValue(msg.sender) >= _amount,
"ERROR_WITHDRAW-VALUE_BADCONDITOONS"
);
_attributions = (totalAttributions * _amount) / valueAll();
attributions[msg.sender] -= _attributions;
totalAttributions -= _attributions;
if (available() < _amount) {
//when USDC in this contract isn't enough
uint256 _shortage = _amount - available();
_unutilize(_shortage);
assert(available() >= _amount);
}
balance -= _amount;
IERC20(token).safeTransfer(_to, _amount);
}
/**
* @notice an address that has balance in the vault can transfer underlying value
* @param _amount sender of value
* @param _destination reciepient of value
*/
function transferValue(uint256 _amount, address _destination)
external
override
returns (uint256 _attributions)
{
require(
attributions[msg.sender] > 0 &&
underlyingValue(msg.sender) >= _amount,
"ERROR_TRANSFER-VALUE_BADCONDITOONS"
);
_attributions = (_amount * totalAttributions) / valueAll();
attributions[msg.sender] -= _attributions;
attributions[_destination] += _attributions;
}
/**
* @notice a registered contract can borrow balance from the vault
* @param _amount borrow amount
* @param _to borrower's address
*/
function borrowValue(uint256 _amount, address _to) external onlyMarket override {
debts[msg.sender] += _amount;
totalDebt += _amount;
IERC20(token).safeTransfer(_to, _amount);
}
/**
* @notice an address that has balance in the vault can offset an address's debt
* @param _amount debt amount to offset
* @param _target borrower's address
*/
function offsetDebt(uint256 _amount, address _target)
external
override
returns (uint256 _attributions)
{
require(
attributions[msg.sender] > 0 &&
underlyingValue(msg.sender) >= _amount,
"ERROR_REPAY_DEBT_BADCONDITOONS"
);
_attributions = (_amount * totalAttributions) / valueAll();
attributions[msg.sender] -= _attributions;
totalAttributions -= _attributions;
balance -= _amount;
debts[_target] -= _amount;
totalDebt -= _amount;
}
/**
* @notice a registerd market can transfer their debt to system debt
* @param _amount debt amount to transfer
* @dev will be called when CDS could not afford when resume the market.
*/
function transferDebt(uint256 _amount) external onlyMarket override {
if(_amount != 0){
debts[msg.sender] -= _amount;
debts[address(0)] += _amount;
}
}
/**
* @notice anyone can repay the system debt by sending tokens to this contract
* @param _amount debt amount to repay
* @param _target borrower's address
*/
function repayDebt(uint256 _amount, address _target) external override {
uint256 _debt = debts[_target];
if (_debt >= _amount) {
debts[_target] -= _amount;
totalDebt -= _amount;
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
} else {
debts[_target] = 0;
totalDebt -= _debt;
IERC20(token).safeTransferFrom(msg.sender, address(this), _debt);
}
}
/**
* @notice an address that has balance in the vault can withdraw value denominated in attribution
* @param _attribution amount of attribution to burn
* @param _to beneficiary's address
* @return _retVal number of tokens withdrawn from the transaction
*/
function withdrawAttribution(uint256 _attribution, address _to)
external
override
returns (uint256 _retVal)
{
_retVal = _withdrawAttribution(_attribution, _to);
}
/**
* @notice an address that has balance in the vault can withdraw all value
* @param _to beneficiary's address
* @return _retVal number of tokens withdrawn from the transaction
*/
function withdrawAllAttribution(address _to)
external
override
returns (uint256 _retVal)
{
_retVal = _withdrawAttribution(attributions[msg.sender], _to);
}
/**
* @notice an address that has balance in the vault can withdraw all value
* @param _attribution amount of attribution to burn
* @param _to beneficiary's address
* @return _retVal number of tokens withdrawn from the transaction
*/
function _withdrawAttribution(uint256 _attribution, address _to)
internal
returns (uint256 _retVal)
{
require(
attributions[msg.sender] >= _attribution,
"ERROR_WITHDRAW-ATTRIBUTION_BADCONDITOONS"
);
_retVal = (_attribution * valueAll()) / totalAttributions;
attributions[msg.sender] -= _attribution;
totalAttributions -= _attribution;
if (available() < _retVal) {
uint256 _shortage = _retVal - available();
_unutilize(_shortage);
}
balance -= _retVal;
IERC20(token).safeTransfer(_to, _retVal);
}
/**
* @notice an address that has balance in the vault can transfer value denominated in attribution
* @param _amount amount of attribution to transfer
* @param _destination reciepient of attribution
*/
function transferAttribution(uint256 _amount, address _destination)
external
override
{
require(_destination != address(0), "ERROR_ZERO_ADDRESS");
require(
_amount != 0 && attributions[msg.sender] >= _amount,
"ERROR_TRANSFER-ATTRIBUTION_BADCONDITOONS"
);
attributions[msg.sender] -= _amount;
attributions[_destination] += _amount;
}
/**
* @notice the controller can utilize all available stored funds
* @return _amount amount of tokens utilized
*/
function utilize() external override returns (uint256 _amount) {
if (keeper != address(0)) {
require(msg.sender == keeper, "ERROR_NOT_KEEPER");
}
_amount = available();
//balance
if (_amount > 0) {
IERC20(token).safeTransfer(address(controller), _amount);
balance -= _amount;
controller.earn(address(token), _amount);
}
}
/**
* @notice get attribution number for the specified address
* @param _target target address
* @return amount of attritbution
*/
function attributionOf(address _target)
external
view
override
returns (uint256)
{
return attributions[_target];
}
/**
* @notice get all attribution number for this contract
* @return amount of all attribution
*/
function attributionAll() external view returns (uint256) {
return totalAttributions;
}
/**
* @notice Convert attribution number into underlying assset value
* @param _attribution amount of attribution
* @return token value of input attribution
*/
function attributionValue(uint256 _attribution)
external
view
override
returns (uint256)
{
if (totalAttributions > 0 && _attribution > 0) {
return (_attribution * valueAll()) / totalAttributions;
} else {
return 0;
}
}
/**
* @notice return underlying value of the specified address
* @param _target target address
* @return token value of target address
*/
function underlyingValue(address _target)
public
view
override
returns (uint256)
{
if (attributions[_target] > 0) {
return (valueAll() * attributions[_target]) / totalAttributions;
} else {
return 0;
}
}
/**
* @notice return underlying value of this contract
* @return all token value of the vault
*/
function valueAll() public view returns (uint256) {
if (address(controller) != address(0)) {
return balance + controller.valueAll();
} else {
return balance;
}
}
/**
* @notice internal function to unutilize the funds and keep utilization rate
* @param _amount amount to withdraw from controller
*/
function _unutilize(uint256 _amount) internal {
require(address(controller) != address(0), "ERROR_CONTROLLER_NOT_SET");
controller.withdraw(address(this), _amount);
balance += _amount;
}
/**
* @notice return how much funds in this contract is available to be utilized
* @return available balance to utilize
*/
function available() public view returns (uint256) {
return balance - totalDebt;
}
/**
* @notice return how much price for each attribution
* @return value of one share of attribution
*/
function getPricePerFullShare() public view returns (uint256) {
return (valueAll() * MAGIC_SCALE_1E6) / totalAttributions;
}
/**
* onlyOwner
*/
/**
* @notice withdraw redundant token stored in this contract
* @param _token token address
* @param _to beneficiary's address
*/
function withdrawRedundant(address _token, address _to)
external
override
onlyOwner
{
if (
_token == address(token) &&
balance < IERC20(token).balanceOf(address(this))
) {
uint256 _redundant = IERC20(token).balanceOf(address(this)) -
balance;
IERC20(token).safeTransfer(_to, _redundant);
} else if (IERC20(_token).balanceOf(address(this)) > 0) {
IERC20(_token).safeTransfer(
_to,
IERC20(_token).balanceOf(address(this))
);
}
}
/**
* @notice admin function to set controller address
* @param _controller address of the controller
*/
function setController(address _controller) public override onlyOwner {
require(_controller != address(0), "ERROR_ZERO_ADDRESS");
if (address(controller) != address(0)) {
controller.migrate(address(_controller));
controller = IController(_controller);
} else {
controller = IController(_controller);
}
emit ControllerSet(_controller);
}
/**
* @notice the controller can utilize all available stored funds
* @param _keeper keeper address
*/
function setKeeper(address _keeper) external override onlyOwner {
if (keeper != _keeper) {
keeper = _keeper;
}
}
} | 3,531 | 513 | 1 | 1. [H-01] Tokens can be burned with no access control L382 (Access control)
The Vault.sol contract has two address state variables, the keeper variable and the controller variable, which are both permitted to be the zero address. If both variables are zero simultaneously, any address can burn the available funds (available funds = balance - totalDebt) by sending these tokens to the zero address with the unprotected utilitize() function.
2. [H-05] backdoor in withdrawRedundant (Centralization Risk)
The Vault.withdrawRedundant has wrong logic that allows the admins to steal the underlying vault token.
3. [H-07] Wrong design/implementation of permission control allows malicious/compromised Registry or Factory admin to steal funds from users' wallet balances. (Ownership)
`onlyMarket()` and `addValue` function
4. [H-09] Vault#setController() owner of the Vault contracts can drain funds from the Vault (Owner action, Centralization Risk)
5. [H-10] A malicious/compromised Registry or Factory admin can drain all the funds from the Vault contracts (Ownership)
`onlyMarket()` and `borrowValue()` function
6. [M-01] repayDebt in Vault.sol could DOS functionality for markets
Any user can pay the debt for any borrower in Vault.sol, by using repayDebt(). This function allows anyone to repay any amount of borrowed value, up-to and including the totalDebt value; it works by setting the debts[_target] to zero, and decreasing totalDebt by the given amount, up to zero. However, all debts of the other borrowers are left untouched.
7. [M-05] Vault.sol Tokens with fee on transfer are not supported
Vault.sol#addValue() assumes that the received amount is the same as the transfer amount, and uses it to calculate attributions, balance amounts, etc. While the actual transferred amount can be lower for those tokens. | 7 |
31_veCVXStrategy.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
pragma experimental ABIEncoderV2;
import "../deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "../deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import "../deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "../interfaces/uniswap/IUniswapRouterV2.sol";
import "../interfaces/badger/ISettV3.sol";
import "../interfaces/badger/IController.sol";
import "../interfaces/cvx/ICvxLocker.sol";
import "../interfaces/snapshot/IDelegateRegistry.sol";
import {BaseStrategy} from "../deps/BaseStrategy.sol";
contract MyStrategy is BaseStrategy {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
uint256 MAX_BPS = 10_000;
// address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow
address public lpComponent;
// Token we provide liquidity with
address public reward;
// Token we farm and swap to want / lpComponent
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address public constant SUSHI_ROUTER =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
IDelegateRegistry public constant SNAPSHOT =
IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446);
// The address this strategies delegates voting to
address public constant DELEGATE =
0xB65cef03b9B89f99517643226d76e286ee999e77;
bytes32 public constant DELEGATED_SPACE =
0x6376782e65746800000000000000000000000000000000000000000000000000;
ICvxLocker public LOCKER;
ISettV3 public CVX_VAULT =
ISettV3(0x53C8E199eb2Cb7c01543C137078a038937a68E40);
bool public withdrawalSafetyCheck = true;
bool public harvestOnRebalance = true;
// If nothing is unlocked, processExpiredLocks will revert
bool public processLocksOnReinvest = true;
bool public processLocksOnRebalance = true;
event Debug(string name, uint256 value);
// Used to signal to the Badger Tree that rewards where sent to it
event TreeDistribution(
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[3] memory _wantConfig,
uint256[3] memory _feeConfig,
address _locker
///@dev TODO: Add this to deploy
) public initializer {
__BaseStrategy_init(
_governance,
_strategist,
_controller,
_keeper,
_guardian
);
/// @dev Add config here
want = _wantConfig[0];
lpComponent = _wantConfig[1];
reward = _wantConfig[2];
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
LOCKER = ICvxLocker(_locker);
//TODO: Make locker hardcoded at top of file
/// @dev do one off approvals here
// IERC20Upgradeable(want).safeApprove(gauge, type(uint256).max);
// Permissions for Locker
IERC20Upgradeable(CVX).safeApprove(_locker, type(uint256).max);
IERC20Upgradeable(CVX).safeApprove(
address(CVX_VAULT),
type(uint256).max
);
// Permissions for Sushiswap
IERC20Upgradeable(reward).safeApprove(SUSHI_ROUTER, type(uint256).max);
// Delegate voting to DELEGATE
SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE);
}
/// ===== Extra Functions =====
///@dev Should we check if the amount requested is more than what we can return on withdrawal?
function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) public {
_onlyGovernance();
withdrawalSafetyCheck = newWithdrawalSafetyCheck;
}
///@dev Should we harvest before doing manual rebalancing
///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out
function setHarvestOnRebalance(bool newHarvestOnRebalance) public {
_onlyGovernance();
harvestOnRebalance = newHarvestOnRebalance;
}
///@dev Should we processExpiredLocks during reinvest?
function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) public {
_onlyGovernance();
processLocksOnReinvest = newProcessLocksOnReinvest;
}
///@dev Should we processExpiredLocks during manualRebalance?
function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance)
public
{
_onlyGovernance();
processLocksOnRebalance = newProcessLocksOnRebalance;
}
/// ===== View Functions =====
/// @dev Specify the name of the strategy
function getName() external pure override returns (string memory) {
return "veCVX Voting Strategy";
}
/// @dev Specify the version of the Strategy, for upgrades
function version() external pure returns (string memory) {
return "1.0";
}
/// @dev From CVX Token to Helper Vault Token
function CVXToWant(uint256 cvx) public view returns (uint256) {
uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare();
return cvx.mul(10**18).div(bCVXToCVX);
}
/// @dev From Helper Vault Token to CVX Token
function wantToCVX(uint256 want) public view returns (uint256) {
uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare();
return want.mul(bCVXToCVX).div(10**18);
}
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public view override returns (uint256) {
if (withdrawalSafetyCheck) {
uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare();
// 18 decimals
require(bCVXToCVX > 10**18, "Loss Of Peg");
// Avoid trying to redeem for less / loss of peg
}
// Return the balance in locker + unlocked but not withdrawn, better estimate to allow some withdrawals
// then multiply it by the price per share as we need to convert CVX to bCVX
uint256 valueInLocker =
CVXToWant(LOCKER.lockedBalanceOf(address(this))).add(
CVXToWant(IERC20Upgradeable(CVX).balanceOf(address(this)))
);
return (valueInLocker);
}
/// @dev Returns true if this strategy requires tending
function isTendable() public view override returns (bool) {
return false;
}
// @dev These are the tokens that cannot be moved except by the vault
function getProtectedTokens()
public
view
override
returns (address[] memory)
{
address[] memory protectedTokens = new address[](4);
protectedTokens[0] = want;
protectedTokens[1] = lpComponent;
protectedTokens[2] = reward;
protectedTokens[3] = CVX;
return protectedTokens;
}
/// ===== Permissioned Actions: Governance =====
/// @notice Delete if you don't need!
function setKeepReward(uint256 _setKeepReward) external {
_onlyGovernance();
}
/// ===== Internal Core Implementations =====
/// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat
function _onlyNotProtectedTokens(address _asset) internal override {
address[] memory protectedTokens = getProtectedTokens();
for (uint256 x = 0; x < protectedTokens.length; x++) {
require(
address(protectedTokens[x]) != _asset,
"Asset is protected"
);
}
}
/// @dev invest the amount of want
/// @notice When this function is called, the controller has already sent want to this
/// @notice Just get the current balance and then invest accordingly
function _deposit(uint256 _amount) internal override {
// We receive bCVX -> Convert to bCVX
CVX_VAULT.withdraw(_amount);
uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this));
// Lock tokens for 17 weeks, send credit to strat, always use max boost cause why not?
LOCKER.lock(address(this), toDeposit, LOCKER.maximumBoostPayment());
}
/// @dev utility function to convert all we can to bCVX
/// @notice You may want to harvest before calling this to maximize the amount of bCVX you'll have
function prepareWithdrawAll() external {
_onlyGovernance();
LOCKER.processExpiredLocks(false);
uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this));
if (toDeposit > 0) {
CVX_VAULT.deposit(toDeposit);
}
}
/// @dev utility function to withdraw everything for migration
/// @dev NOTE: You cannot call this unless you have rebalanced to have only bCVX left in the vault
function _withdrawAll() internal override {
//NOTE: This probably will always fail unless we have all tokens expired
require(
LOCKER.lockedBalanceOf(address(this)) == 0 &&
LOCKER.balanceOf(address(this)) == 0,
"You have to wait for unlock and have to manually rebalance out of it"
);
// NO-OP because you can't deposit AND transfer with bCVX
// See prepareWithdrawAll above
}
/// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
uint256 max = IERC20Upgradeable(want).balanceOf(address(this));
if (withdrawalSafetyCheck) {
uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare();
// 18 decimals
require(bCVXToCVX > 10**18, "Loss Of Peg");
// Avoid trying to redeem for less / loss of peg
require(
max >= _amount.mul(9_980).div(MAX_BPS),
"Withdrawal Safety Check"
);
// 20 BP of slippage
}
if (max < _amount) {
return max;
}
return _amount;
}
/// @dev Harvest from strategy mechanics, realizing increase in underlying position
function harvest() public whenNotPaused returns (uint256 harvested) {
_onlyAuthorizedActors();
uint256 _before = IERC20Upgradeable(want).balanceOf(address(this));
uint256 _beforeCVX = IERC20Upgradeable(reward).balanceOf(address(this));
// Get cvxCRV
LOCKER.getReward(address(this), false);
// Rewards Math
uint256 earnedReward =
IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeCVX);
// Because we are using bCVX we take fees in reward
//NOTE: This will probably revert because we deposit and transfer on same block
(uint256 governancePerformanceFee, uint256 strategistPerformanceFee) =
_processRewardsFees(earnedReward, reward);
// Swap cvxCRV for want (bCVX)
_swapcvxCRVToWant();
uint256 earned =
IERC20Upgradeable(want).balanceOf(address(this)).sub(_before);
/// @dev Harvest event that every strategy MUST have, see BaseStrategy
emit Harvest(earned, block.number);
/// @dev Harvest must return the amount of want increased
return earned;
}
/// @dev Rebalance, Compound or Pay off debt here
function tend() external whenNotPaused {
_onlyAuthorizedActors();
revert();
// NOTE: For now tend is replaced by manualRebalance
}
/// @dev Swap from reward to CVX, then deposit into bCVX vault
function _swapcvxCRVToWant() internal {
uint256 toSwap = IERC20Upgradeable(reward).balanceOf(address(this));
if (toSwap == 0) {
return;
}
// Sushi reward to WETH to want
address[] memory path = new address[](3);
path[0] = reward;
path[1] = WETH;
path[2] = CVX;
IUniswapRouterV2(SUSHI_ROUTER).swapExactTokensForTokens(
toSwap,
0,
path,
address(this),
now
);
// Deposit into vault
uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this));
if (toDeposit > 0) {
CVX_VAULT.deposit(toDeposit);
}
}
/// ===== Internal Helper Functions =====
/// @dev used to manage the governance and strategist fee, make sure to use it to get paid!
function _processPerformanceFees(uint256 _amount)
internal
returns (
uint256 governancePerformanceFee,
uint256 strategistPerformanceFee
)
{
governancePerformanceFee = _processFee(
want,
_amount,
performanceFeeGovernance,
IController(controller).rewards()
);
strategistPerformanceFee = _processFee(
want,
_amount,
performanceFeeStrategist,
strategist
);
}
/// @dev used to manage the governance and strategist fee on earned rewards, make sure to use it to get paid!
function _processRewardsFees(uint256 _amount, address _token)
internal
returns (uint256 governanceRewardsFee, uint256 strategistRewardsFee)
{
governanceRewardsFee = _processFee(
_token,
_amount,
performanceFeeGovernance,
IController(controller).rewards()
);
strategistRewardsFee = _processFee(
_token,
_amount,
performanceFeeStrategist,
strategist
);
}
/// MANUAL FUNCTIONS ///
/// @dev manual function to reinvest all CVX that was locked
function reinvest() external whenNotPaused returns (uint256 reinvested) {
_onlyGovernance();
if (processLocksOnReinvest) {
// Withdraw all we can
LOCKER.processExpiredLocks(false);
}
// Redeposit all into veCVX
uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this));
// Redeposit into veCVX
LOCKER.lock(address(this), toDeposit, LOCKER.maximumBoostPayment());
}
/// @dev process all locks, to redeem
function manualProcessExpiredLocks() external whenNotPaused {
_onlyGovernance();
LOCKER.processExpiredLocks(false);
// Unlock veCVX that is expired and redeem CVX back to this strat
// Processed in the next harvest or during prepareMigrateAll
}
/// @dev Take all CVX and deposits in the CVX_VAULT
function manualDepositCVXIntoVault() external whenNotPaused {
_onlyGovernance();
uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this));
if (toDeposit > 0) {
CVX_VAULT.deposit(toDeposit);
}
}
/// @dev Send all available bCVX to the Vault
/// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool
function manualSendbCVXToVault() external whenNotPaused {
_onlyGovernance();
uint256 bCvxAmount = IERC20Upgradeable(want).balanceOf(address(this));
_transferToVault(bCvxAmount);
}
/// @dev use the currently available CVX to either lock or add to bCVX
/// @notice toLock = 0, lock nothing, deposit in bCVX as much as you can
/// @notice toLock = 100, lock everything (CVX) you have
function manualRebalance(uint256 toLock) external whenNotPaused {
_onlyGovernance();
require(toLock <= MAX_BPS, "Max is 100%");
if (processLocksOnRebalance) {
// manualRebalance will revert if you have no expired locks
LOCKER.processExpiredLocks(false);
}
if (harvestOnRebalance) {
harvest();
}
// Token that is highly liquid
uint256 balanceOfWant =
IERC20Upgradeable(want).balanceOf(address(this));
// CVX uninvested we got from harvest and unlocks
uint256 balanceOfCVX = IERC20Upgradeable(CVX).balanceOf(address(this));
// Locked CVX in the locker
uint256 balanceInLock = LOCKER.balanceOf(address(this));
uint256 totalCVXBalance =
balanceOfCVX.add(balanceInLock).add(wantToCVX(balanceOfWant));
//Ratios
uint256 currentLockRatio =
balanceInLock.mul(10**18).div(totalCVXBalance);
// Amount we want to have in lock
uint256 newLockRatio = totalCVXBalance.mul(toLock).div(MAX_BPS);
// Amount we want to have in bCVX
uint256 toWantRatio =
totalCVXBalance.mul(MAX_BPS.sub(toLock)).div(MAX_BPS);
// We can't unlock enough, just deposit rest into bCVX
if (newLockRatio <= currentLockRatio) {
// Deposit into vault
uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this));
if (toDeposit > 0) {
CVX_VAULT.deposit(toDeposit);
}
return;
}
// If we're continuing, then we are going to lock something (unless it's zero)
uint256 cvxToLock = newLockRatio.sub(currentLockRatio);
// NOTE: We only lock the CVX we have and not the bCVX
// bCVX should be sent back to vault and then go through earn
// We do this because bCVX has "blockLock" and we can't both deposit and withdraw on the same block
uint256 maxCVX = IERC20Upgradeable(CVX).balanceOf(address(this));
if (cvxToLock > maxCVX) {
// Just lock what we can
LOCKER.lock(address(this), maxCVX, LOCKER.maximumBoostPayment());
} else {
// Lock proper
LOCKER.lock(address(this), cvxToLock, LOCKER.maximumBoostPayment());
}
// If anything else is left, deposit into vault
uint256 cvxLeft = IERC20Upgradeable(CVX).balanceOf(address(this));
if (cvxLeft > 0) {
CVX_VAULT.deposit(cvxLeft);
}
// At the end of the rebalance, there won't be any balanceOfCVX as that token is not considered by our strat
}
} | 4,510 | 520 | 0 | 1. [H-01] veCVXStrategy.manualRebalance has wrong logic
The `veCVXStrategy.manualRebalance` function computes two ratios `currentLockRatio` and `newLockRatio` and compares them. However, these ratios compute different things and are not comparable. | 1 |
14_IdleYieldSource.sol | // SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./interfaces/pooltogether/IProtocolYieldSource.sol";
import "./interfaces/idle/IIdleToken.sol";
import "./access/AssetManager.sol";
/// @title An pooltogether yield source for Idle token
/// @author Sunny Radadiya
contract IdleYieldSource is IProtocolYieldSource, Initializable, ReentrancyGuardUpgradeable, ERC20Upgradeable, AssetManager {
using SafeERC20Upgradeable for IERC20Upgradeable;
address public idleToken;
address public underlyingAsset;
uint256 public constant ONE_IDLE_TOKEN = 10**18;
/// @notice Emitted when the yield source is initialized
event IdleYieldSourceInitialized(address indexed idleToken);
/// @notice Emitted when asset tokens are redeemed from the yield source
event RedeemedToken(
address indexed from,
uint256 shares,
uint256 amount
);
/// @notice Emitted when asset tokens are supplied to the yield source
event SuppliedTokenTo(
address indexed from,
uint256 shares,
uint256 amount,
address indexed to
);
/// @notice Emitted when asset tokens are supplied to sponsor the yield source
event Sponsored(
address indexed from,
uint256 amount
);
/// @notice Emitted when ERC20 tokens other than yield source's idleToken are withdrawn from the yield source
event TransferredERC20(
address indexed from,
address indexed to,
uint256 amount,
address indexed token
);
/// @notice Initializes the yield source with Idle Token
/// @param _idleToken Idle Token address
function initialize(
address _idleToken
) public initializer {
__Ownable_init();
idleToken = _idleToken;
underlyingAsset = IIdleToken(idleToken).token();
IERC20Upgradeable(underlyingAsset).safeApprove(idleToken, type(uint256).max);
emit IdleYieldSourceInitialized(idleToken);
}
/// @notice Returns the ERC20 asset token used for deposits.
/// @return The ERC20 asset token
function depositToken() external view override returns (address) {
return underlyingAsset;
}
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function balanceOfToken(address addr) external view override returns (uint256) {
return _sharesToToken(balanceOf(addr));
}
/// @notice Calculates the balance of Total idle Tokens Contract hasv
/// @return balance of Idle Tokens
function _totalShare() internal view returns(uint256) {
return IIdleToken(idleToken).balanceOf(address(this));
}
/// @notice Calculates the number of shares that should be mint or burned when a user deposit or withdraw
/// @param tokens Amount of tokens
/// return Number of shares
function _tokenToShares(uint256 tokens) internal view returns (uint256 shares) {
shares = (tokens * ONE_IDLE_TOKEN) / _price();
}
/// @notice Calculates the number of tokens a user has in the yield source
/// @param shares Amount of shares
/// return Number of tokens
function _sharesToToken(uint256 shares) internal view returns (uint256 tokens) {
tokens = (shares * _price()) / ONE_IDLE_TOKEN;
}
/// @notice Calculates the current price per share
/// @return avg idleToken price for this contract
function _price() internal view returns (uint256) {
return IIdleToken(idleToken).tokenPriceWithFee(address(this));
}
/// @notice Deposit asset tokens to Idle
/// @param mintAmount The amount of asset tokens to be deposited
/// @return number of minted tokens
function _depositToIdle(uint256 mintAmount) internal returns (uint256) {
IERC20Upgradeable(underlyingAsset).safeTransferFrom(msg.sender, address(this), mintAmount);
return IIdleToken(idleToken).mintIdleToken(mintAmount, false, address(0));
}
/// @notice Allows assets to be supplied on other user's behalf using the `to` param.
/// @param mintAmount The amount of `token()` to be supplied
/// @param to The user whose balance will receive the tokens
function supplyTokenTo(uint256 mintAmount, address to) external nonReentrant override {
uint256 mintedTokenShares = _tokenToShares(mintAmount);
_depositToIdle(mintAmount);
_mint(to, mintedTokenShares);
emit SuppliedTokenTo(msg.sender, mintedTokenShares, mintAmount, to);
}
/// @notice Redeems tokens from the yield source from the msg.sender, it burn yield bearing tokens and return token to the sender.
/// @param redeemAmount The amount of `token()` to withdraw. Denominated in `token()` as above.
/// @return redeemedUnderlyingAsset The actual amount of tokens that were redeemed.
function redeemToken(uint256 redeemAmount) external override nonReentrant returns (uint256 redeemedUnderlyingAsset) {
uint256 redeemedShare = _tokenToShares(redeemAmount);
_burn(msg.sender, redeemedShare);
redeemedUnderlyingAsset = IIdleToken(idleToken).redeemIdleToken(redeemedShare);
IERC20Upgradeable(underlyingAsset).safeTransfer(msg.sender, redeemedUnderlyingAsset);
emit RedeemedToken(msg.sender, redeemedShare, redeemAmount);
}
/// @notice Transfer ERC20 tokens other than the idleTokens held by this contract to the recipient address
/// @dev This function is only callable by the owner or asset manager
/// @param erc20Token The ERC20 token to transfer
/// @param to The recipient of the tokens
/// @param amount The amount of tokens to transfer
function transferERC20(address erc20Token, address to, uint256 amount) external override onlyOwnerOrAssetManager {
require(erc20Token != idleToken, "IdleYieldSource/idleDai-transfer-not-allowed");
IERC20Upgradeable(erc20Token).safeTransfer(to, amount);
emit TransferredERC20(msg.sender, to, amount, erc20Token);
}
/// @notice Allows someone to deposit into the yield source without receiving any shares
/// @dev This allows anyone to distribute tokens among the share holders
/// @param amount The amount of tokens to deposit
function sponsor(uint256 amount) external override {
_depositToIdle(amount);
emit Sponsored(msg.sender, amount);
}
} | 1,516 | 154 | 1 | 1. [H-01] User could lose underlying tokens when redeeming from the IdleYieldSource
The `redeemToken` function in IdleYieldSource uses redeemedShare instead of redeemAmount as the input parameter when calling redeemIdleToken of the Idle yield source. As a result, users could get fewer underlying tokens than they should.
2. H-05: IdleYieldSource doesn't use `mantissa` calculations (Calculation decimals)
Because mantissa calculations are not used in this case to account for decimals, the arithmetic can zero out the number of shares or tokens that should be given.
3. M-03: SafeMath not completely used in yield source contracts (overflow)
`_tokenToShares` function, `shares = (tokens * ONE_IDLE_TOKEN) / _price();` | 3 |
36_Basket.sol | pragma solidity =0.8.7;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import './interfaces/IAuction.sol';
import "./interfaces/IBasket.sol";
import "./interfaces/IFactory.sol";
import "hardhat/console.sol";
contract Basket is IBasket, ERC20Upgradeable {
using SafeERC20 for IERC20;
uint256 public constant TIMELOCK_DURATION = 4 * 60 * 24;
// 1 day
uint256 public constant ONE_YEAR = 365.25 days;
uint256 private constant BASE = 1e18;
address public publisher;
uint256 public licenseFee;
IFactory public override factory;
IAuction public override auction;
uint256 public override ibRatio;
PendingPublisher public pendingPublisher;
PendingLicenseFee public pendingLicenseFee;
PendingWeights public pendingWeights;
address[] public tokens;
uint256[] public weights;
uint256 public override lastFee;
function initialize(IFactory.Proposal memory proposal, IAuction auction_) public override {
publisher = proposal.proposer;
licenseFee = proposal.licenseFee;
factory = IFactory(msg.sender);
auction = auction_;
ibRatio = BASE;
tokens = proposal.tokens;
weights = proposal.weights;
approveUnderlying(address(auction));
__ERC20_init(proposal.tokenName, proposal.tokenSymbol);
}
function getPendingWeights() external override view returns (address[] memory, uint256[] memory) {
return (pendingWeights.tokens, pendingWeights.weights);
}
function validateWeights(address[] memory _tokens, uint256[] memory _weights) public override pure {
require(_tokens.length == _weights.length);
uint256 length = _tokens.length;
address[] memory tokenList = new address[](length);
// check uniqueness of tokens and not token(0)
for (uint i = 0; i < length; i++) {
require(_tokens[i] != address(0));
require(_weights[i] > 0);
for (uint256 x = 0; x < tokenList.length; x++) {
require(_tokens[i] != tokenList[x]);
}
tokenList[i] = _tokens[i];
}
}
function mint(uint256 amount) public override {
mintTo(amount, msg.sender);
}
function mintTo(uint256 amount, address to) public override {
require(auction.auctionOngoing() == false);
require(amount > 0);
handleFees();
pullUnderlying(amount, msg.sender);
_mint(to, amount);
emit Minted(to, amount);
}
function burn(uint256 amount) public override {
require(auction.auctionOngoing() == false);
require(amount > 0);
require(balanceOf(msg.sender) >= amount);
handleFees();
pushUnderlying(amount, msg.sender);
_burn(msg.sender, amount);
emit Burned(msg.sender, amount);
}
function auctionBurn(uint256 amount) onlyAuction external override {
handleFees();
_burn(msg.sender, amount);
emit Burned(msg.sender, amount);
}
function handleFees() private {
if (lastFee == 0) {
lastFee = block.timestamp;
} else {
uint256 startSupply = totalSupply();
uint256 timeDiff = (block.timestamp - lastFee);
uint256 feePct = timeDiff * licenseFee / ONE_YEAR;
uint256 fee = startSupply * feePct / (BASE - feePct);
_mint(publisher, fee * (BASE - factory.ownerSplit()) / BASE);
_mint(Ownable(address(factory)).owner(), fee * factory.ownerSplit() / BASE);
lastFee = block.timestamp;
uint256 newIbRatio = ibRatio * startSupply / totalSupply();
ibRatio = newIbRatio;
emit NewIBRatio(ibRatio);
}
}
// changes publisher
// timelocked
function changePublisher(address newPublisher) onlyPublisher public override {
require(newPublisher != address(0));
if (pendingPublisher.publisher != address(0)) {
require(pendingPublisher.publisher == newPublisher);
require(block.number >= pendingPublisher.block + TIMELOCK_DURATION);
publisher = pendingPublisher.publisher;
pendingPublisher.publisher = address(0);
emit ChangedPublisher(publisher);
} else {
pendingPublisher.publisher = newPublisher;
pendingPublisher.block = block.number;
}
}
//changes licenseFee
// timelocked
function changeLicenseFee(uint256 newLicenseFee) onlyPublisher public override {
require(newLicenseFee >= factory.minLicenseFee() && newLicenseFee != licenseFee);
if (pendingLicenseFee.licenseFee != 0) {
require(pendingLicenseFee.licenseFee == newLicenseFee);
require(block.number >= pendingLicenseFee.block + TIMELOCK_DURATION);
licenseFee = pendingLicenseFee.licenseFee;
pendingLicenseFee.licenseFee = 0;
emit ChangedLicenseFee(licenseFee);
} else {
pendingLicenseFee.licenseFee = newLicenseFee;
pendingLicenseFee.block = block.number;
}
}
// publish new index
// timelocked
function publishNewIndex(address[] memory _tokens, uint256[] memory _weights) onlyPublisher public override {
validateWeights(_tokens, _weights);
if (pendingWeights.pending) {
require(block.number >= pendingWeights.block + TIMELOCK_DURATION);
if (auction.auctionOngoing() == false) {
auction.startAuction();
emit PublishedNewIndex(publisher);
} else if (auction.hasBonded()) {
} else {
auction.killAuction();
pendingWeights.tokens = _tokens;
pendingWeights.weights = _weights;
pendingWeights.block = block.number;
}
} else {
pendingWeights.pending = true;
pendingWeights.tokens = _tokens;
pendingWeights.weights = _weights;
pendingWeights.block = block.number;
}
}
function setNewWeights() onlyAuction external override {
tokens = pendingWeights.tokens;
weights = pendingWeights.weights;
pendingWeights.pending = false;
approveUnderlying(address(auction));
emit WeightsSet();
}
// delete pending index
function deleteNewIndex() public override {
require(msg.sender == publisher || msg.sender == address(auction));
require(auction.auctionOngoing() == false);
pendingWeights.pending = false;
emit DeletedNewIndex(publisher);
}
function updateIBRatio(uint256 newRatio) onlyAuction external override returns (uint256) {
ibRatio = newRatio;
emit NewIBRatio(ibRatio);
return ibRatio;
}
function approveUnderlying(address spender) private {
for (uint256 i = 0; i < weights.length; i++) {
IERC20(tokens[i]).approve(spender, type(uint256).max);
}
}
function pushUnderlying(uint256 amount, address to) private {
for (uint256 i = 0; i < weights.length; i++) {
uint256 tokenAmount = amount * weights[i] * ibRatio / BASE / BASE;
IERC20(tokens[i]).safeTransfer(to, tokenAmount);
}
}
function pullUnderlying(uint256 amount, address from) private {
for (uint256 i = 0; i < weights.length; i++) {
uint256 tokenAmount = amount * weights[i] * ibRatio / BASE / BASE;
IERC20(tokens[i]).safeTransferFrom(from, address(this), tokenAmount);
}
}
modifier onlyAuction() {
require(msg.sender == address(auction));
_;
}
modifier onlyPublisher() {
require(msg.sender == address(publisher));
_;
}
} | 1,741 | 254 | 3 | 1. H-01: Re-entrancy in `settleAuction` allow stealing all funds (Reentrancy)
Note that the `Basket` contract approved the `Auction` contract with all tokens and the `settleAuction` function allows the auction bonder to transfer all funds out of the basket to themselves.
2. H-02: Basket.sol#auctionBurn() A failed auction will freeze part of the funds (Price manipulation)
Given the `auctionBurn()` function will _burn() the auction bond without updating the ibRatio. Once the bond of a failed auction is burned, the proportional underlying tokens won't be able to be withdrawn, in other words, being frozen in the contract.
3. M-05: Bonding mechanism allows malicious user to DOS auctions.(DoS)
`publishNewIndex()` function
4. [M-06] Basket becomes unusable if everybody burns their shares
`handleFees()` function, ` uint256 newIbRatio = ibRatio * startSupply / totalSupply();`
5. M-09: Fee calculation is potentially incorrect. (overflow)
`uint256 fee = startSupply * feePct / (BASE - feePct);` in handleFees()`
6. [M-14] Basket.sol#handleFees() could potentially cause disruption of minting and burning. L110
7. [M-17] Unsafe approve would halt the auction and burn the bond.
`approveUnderlying` function
8. [M-18] licenseFee can be greater than BASE in `handleFees()`
`uint256 fee = startSupply * feePct / (BASE - feePct);` | 8 |
193_Pair.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "solmate/tokens/ERC20.sol";
import "solmate/tokens/ERC721.sol";
import "solmate/utils/MerkleProofLib.sol";
import "solmate/utils/SafeTransferLib.sol";
import "openzeppelin/utils/math/Math.sol";
import "./LpToken.sol";
import "./Caviar.sol";
/// @title Pair
/// @author out.eth (@outdoteth)
/// @notice A pair of an NFT and a base token that can be used to create and trade fractionalized NFTs.
contract Pair is ERC20, ERC721TokenReceiver {
using SafeTransferLib for address;
using SafeTransferLib for ERC20;
uint256 public constant ONE = 1e18;
uint256 public constant CLOSE_GRACE_PERIOD = 7 days;
address public immutable nft;
address public immutable baseToken;
// address(0) for ETH
bytes32 public immutable merkleRoot;
LpToken public immutable lpToken;
Caviar public immutable caviar;
uint256 public closeTimestamp;
event Add(uint256 baseTokenAmount, uint256 fractionalTokenAmount, uint256 lpTokenAmount);
event Remove(uint256 baseTokenAmount, uint256 fractionalTokenAmount, uint256 lpTokenAmount);
event Buy(uint256 inputAmount, uint256 outputAmount);
event Sell(uint256 inputAmount, uint256 outputAmount);
event Wrap(uint256[] tokenIds);
event Unwrap(uint256[] tokenIds);
event Close(uint256 closeTimestamp);
event Withdraw(uint256 tokenId);
constructor(
address _nft,
address _baseToken,
bytes32 _merkleRoot,
string memory pairSymbol,
string memory nftName,
string memory nftSymbol
) ERC20(string.concat(nftName, " fractional token"), string.concat("f", nftSymbol), 18) {
nft = _nft;
baseToken = _baseToken;
// use address(0) for native ETH
merkleRoot = _merkleRoot;
lpToken = new LpToken(pairSymbol);
caviar = Caviar(msg.sender);
}
// ************************ //
// Core AMM logic //
// *********************** //
/// @notice Adds liquidity to the pair.
/// @param baseTokenAmount The amount of base tokens to add.
/// @param fractionalTokenAmount The amount of fractional tokens to add.
/// @param minLpTokenAmount The minimum amount of LP tokens to mint.
/// @return lpTokenAmount The amount of LP tokens minted.
function add(uint256 baseTokenAmount, uint256 fractionalTokenAmount, uint256 minLpTokenAmount)
public
payable
returns (uint256 lpTokenAmount)
{
// *** Checks *** //
// check the token amount inputs are not zero
require(baseTokenAmount > 0 && fractionalTokenAmount > 0, "Input token amount is zero");
// check that correct eth input was sent - if the baseToken equals address(0) then native ETH is used
require(baseToken == address(0) ? msg.value == baseTokenAmount : msg.value == 0, "Invalid ether input");
// calculate the lp token shares to mint
lpTokenAmount = addQuote(baseTokenAmount, fractionalTokenAmount);
// check that the amount of lp tokens outputted is greater than the min amount
require(lpTokenAmount >= minLpTokenAmount, "Slippage: lp token amount out");
// *** Effects *** //
// transfer fractional tokens in
_transferFrom(msg.sender, address(this), fractionalTokenAmount);
// *** Interactions *** //
// mint lp tokens to sender
lpToken.mint(msg.sender, lpTokenAmount);
// transfer base tokens in if the base token is not ETH
if (baseToken != address(0)) {
// transfer base tokens in
ERC20(baseToken).safeTransferFrom(msg.sender, address(this), baseTokenAmount);
}
emit Add(baseTokenAmount, fractionalTokenAmount, lpTokenAmount);
}
/// @notice Removes liquidity from the pair.
/// @param lpTokenAmount The amount of LP tokens to burn.
/// @param minBaseTokenOutputAmount The minimum amount of base tokens to receive.
/// @param minFractionalTokenOutputAmount The minimum amount of fractional tokens to receive.
/// @return baseTokenOutputAmount The amount of base tokens received.
/// @return fractionalTokenOutputAmount The amount of fractional tokens received.
function remove(uint256 lpTokenAmount, uint256 minBaseTokenOutputAmount, uint256 minFractionalTokenOutputAmount)
public
returns (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount)
{
// *** Checks *** //
// calculate the output amounts
(baseTokenOutputAmount, fractionalTokenOutputAmount) = removeQuote(lpTokenAmount);
// check that the base token output amount is greater than the min amount
require(baseTokenOutputAmount >= minBaseTokenOutputAmount, "Slippage: base token amount out");
// check that the fractional token output amount is greater than the min amount
require(fractionalTokenOutputAmount >= minFractionalTokenOutputAmount, "Slippage: fractional token out");
// *** Effects *** //
// transfer fractional tokens to sender
_transferFrom(address(this), msg.sender, fractionalTokenOutputAmount);
// *** Interactions *** //
// burn lp tokens from sender
lpToken.burn(msg.sender, lpTokenAmount);
if (baseToken == address(0)) {
// if base token is native ETH then send ether to sender
msg.sender.safeTransferETH(baseTokenOutputAmount);
} else {
// transfer base tokens to sender
ERC20(baseToken).safeTransfer(msg.sender, baseTokenOutputAmount);
}
emit Remove(baseTokenOutputAmount, fractionalTokenOutputAmount, lpTokenAmount);
}
/// @notice Buys fractional tokens from the pair.
/// @param outputAmount The amount of fractional tokens to buy.
/// @param maxInputAmount The maximum amount of base tokens to spend.
/// @return inputAmount The amount of base tokens spent.
function buy(uint256 outputAmount, uint256 maxInputAmount) public payable returns (uint256 inputAmount) {
// *** Checks *** //
// check that correct eth input was sent - if the baseToken equals address(0) then native ETH is used
require(baseToken == address(0) ? msg.value == maxInputAmount : msg.value == 0, "Invalid ether input");
// calculate required input amount using xyk invariant
inputAmount = buyQuote(outputAmount);
// check that the required amount of base tokens is less than the max amount
require(inputAmount <= maxInputAmount, "Slippage: amount in");
// *** Effects *** //
// transfer fractional tokens to sender
_transferFrom(address(this), msg.sender, outputAmount);
// *** Interactions *** //
if (baseToken == address(0)) {
// refund surplus eth
uint256 refundAmount = maxInputAmount - inputAmount;
if (refundAmount > 0) msg.sender.safeTransferETH(refundAmount);
} else {
// transfer base tokens in
ERC20(baseToken).safeTransferFrom(msg.sender, address(this), inputAmount);
}
emit Buy(inputAmount, outputAmount);
}
/// @notice Sells fractional tokens to the pair.
/// @param inputAmount The amount of fractional tokens to sell.
/// @param minOutputAmount The minimum amount of base tokens to receive.
/// @return outputAmount The amount of base tokens received.
function sell(uint256 inputAmount, uint256 minOutputAmount) public returns (uint256 outputAmount) {
// *** Checks *** //
// calculate output amount using xyk invariant
outputAmount = sellQuote(inputAmount);
// check that the outputted amount of fractional tokens is greater than the min amount
require(outputAmount >= minOutputAmount, "Slippage: amount out");
// *** Effects *** //
// transfer fractional tokens from sender
_transferFrom(msg.sender, address(this), inputAmount);
// *** Interactions *** //
if (baseToken == address(0)) {
// transfer ether out
msg.sender.safeTransferETH(outputAmount);
} else {
// transfer base tokens out
ERC20(baseToken).safeTransfer(msg.sender, outputAmount);
}
emit Sell(inputAmount, outputAmount);
}
// ******************** //
// Wrap logic //
// ******************** //
/// @notice Wraps NFTs into fractional tokens.
/// @param tokenIds The ids of the NFTs to wrap.
/// @param proofs The merkle proofs for the NFTs proving that they can be used in the pair.
/// @return fractionalTokenAmount The amount of fractional tokens minted.
function wrap(uint256[] calldata tokenIds, bytes32[][] calldata proofs)
public
returns (uint256 fractionalTokenAmount)
{
// *** Checks *** //
// check that wrapping is not closed
require(closeTimestamp == 0, "Wrap: closed");
// check the tokens exist in the merkle root
_validateTokenIds(tokenIds, proofs);
// *** Effects *** //
// mint fractional tokens to sender
fractionalTokenAmount = tokenIds.length * ONE;
_mint(msg.sender, fractionalTokenAmount);
// *** Interactions *** //
// transfer nfts from sender
for (uint256 i = 0; i < tokenIds.length; i++) {
ERC721(nft).safeTransferFrom(msg.sender, address(this), tokenIds[i]);
}
emit Wrap(tokenIds);
}
/// @notice Unwraps fractional tokens into NFTs.
/// @param tokenIds The ids of the NFTs to unwrap.
/// @return fractionalTokenAmount The amount of fractional tokens burned.
function unwrap(uint256[] calldata tokenIds) public returns (uint256 fractionalTokenAmount) {
// *** Effects *** //
// burn fractional tokens from sender
fractionalTokenAmount = tokenIds.length * ONE;
_burn(msg.sender, fractionalTokenAmount);
// *** Interactions *** //
// transfer nfts to sender
for (uint256 i = 0; i < tokenIds.length; i++) {
ERC721(nft).safeTransferFrom(address(this), msg.sender, tokenIds[i]);
}
emit Unwrap(tokenIds);
}
// *********************** //
// NFT AMM logic //
// *********************** //
/// @notice nftAdd Adds liquidity to the pair using NFTs.
/// @param baseTokenAmount The amount of base tokens to add.
/// @param tokenIds The ids of the NFTs to add.
/// @param minLpTokenAmount The minimum amount of lp tokens to receive.
/// @param proofs The merkle proofs for the NFTs.
/// @return lpTokenAmount The amount of lp tokens minted.
function nftAdd(
uint256 baseTokenAmount,
uint256[] calldata tokenIds,
uint256 minLpTokenAmount,
bytes32[][] calldata proofs
) public payable returns (uint256 lpTokenAmount) {
// wrap the incoming NFTs into fractional tokens
uint256 fractionalTokenAmount = wrap(tokenIds, proofs);
// add liquidity using the fractional tokens and base tokens
lpTokenAmount = add(baseTokenAmount, fractionalTokenAmount, minLpTokenAmount);
}
/// @notice Removes liquidity from the pair using NFTs.
/// @param lpTokenAmount The amount of lp tokens to remove.
/// @param minBaseTokenOutputAmount The minimum amount of base tokens to receive.
/// @param tokenIds The ids of the NFTs to remove.
/// @return baseTokenOutputAmount The amount of base tokens received.
/// @return fractionalTokenOutputAmount The amount of fractional tokens received.
function nftRemove(uint256 lpTokenAmount, uint256 minBaseTokenOutputAmount, uint256[] calldata tokenIds)
public
returns (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount)
{
// remove liquidity and send fractional tokens and base tokens to sender
(baseTokenOutputAmount, fractionalTokenOutputAmount) =
remove(lpTokenAmount, minBaseTokenOutputAmount, tokenIds.length * ONE);
// unwrap the fractional tokens into NFTs and send to sender
unwrap(tokenIds);
}
/// @notice Buys NFTs from the pair using base tokens.
/// @param tokenIds The ids of the NFTs to buy.
/// @param maxInputAmount The maximum amount of base tokens to spend.
/// @return inputAmount The amount of base tokens spent.
function nftBuy(uint256[] calldata tokenIds, uint256 maxInputAmount) public payable returns (uint256 inputAmount) {
// buy fractional tokens using base tokens
inputAmount = buy(tokenIds.length * ONE, maxInputAmount);
// unwrap the fractional tokens into NFTs and send to sender
unwrap(tokenIds);
}
/// @notice Sells NFTs to the pair for base tokens.
/// @param tokenIds The ids of the NFTs to sell.
/// @param minOutputAmount The minimum amount of base tokens to receive.
/// @param proofs The merkle proofs for the NFTs.
/// @return outputAmount The amount of base tokens received.
function nftSell(uint256[] calldata tokenIds, uint256 minOutputAmount, bytes32[][] calldata proofs)
public
returns (uint256 outputAmount)
{
// wrap the incoming NFTs into fractional tokens
uint256 inputAmount = wrap(tokenIds, proofs);
// sell fractional tokens for base tokens
outputAmount = sell(inputAmount, minOutputAmount);
}
// ****************************** //
// Emergency exit logic //
// ****************************** //
/// @notice Closes the pair to new wraps.
/// @dev Can only be called by the caviar owner. This is used as an emergency exit in case
/// the caviar owner suspects that the pair has been compromised.
function close() public {
// check that the sender is the caviar owner
require(caviar.owner() == msg.sender, "Close: not owner");
// set the close timestamp with a grace period
closeTimestamp = block.timestamp + CLOSE_GRACE_PERIOD;
// remove the pair from the Caviar contract
caviar.destroy(nft, baseToken, merkleRoot);
emit Close(closeTimestamp);
}
/// @notice Withdraws a particular NFT from the pair.
/// @dev Can only be called by the caviar owner after the close grace period has passed. This
/// is used to auction off the NFTs in the pair in case NFTs get stuck due to liquidity
/// imbalances. Proceeds from the auction should be distributed pro rata to fractional
/// token holders. See documentation for more details.
function withdraw(uint256 tokenId) public {
// check that the sender is the caviar owner
require(caviar.owner() == msg.sender, "Withdraw: not owner");
// check that the close period has been set
require(closeTimestamp != 0, "Withdraw not initiated");
// check that the close grace period has passed
require(block.timestamp >= closeTimestamp, "Not withdrawable yet");
// transfer the nft to the caviar owner
ERC721(nft).safeTransferFrom(address(this), msg.sender, tokenId);
emit Withdraw(tokenId);
}
// ***************** //
// Getters //
// ***************** //
function baseTokenReserves() public view returns (uint256) {
return _baseTokenReserves();
}
function fractionalTokenReserves() public view returns (uint256) {
return balanceOf[address(this)];
}
/// @notice The current price of one fractional token in base tokens with 18 decimals of precision.
/// @dev Calculated by dividing the base token reserves by the fractional token reserves.
/// @return price The price of one fractional token in base tokens * 1e18.
function price() public view returns (uint256) {
return (_baseTokenReserves() * ONE) / fractionalTokenReserves();
}
/// @notice The amount of base tokens required to buy a given amount of fractional tokens.
/// @dev Calculated using the xyk invariant and a 30bps fee.
/// @param outputAmount The amount of fractional tokens to buy.
/// @return inputAmount The amount of base tokens required.
function buyQuote(uint256 outputAmount) public view returns (uint256) {
return (outputAmount * 1000 * baseTokenReserves()) / ((fractionalTokenReserves() - outputAmount) * 997);
}
/// @notice The amount of base tokens received for selling a given amount of fractional tokens.
/// @dev Calculated using the xyk invariant and a 30bps fee.
/// @param inputAmount The amount of fractional tokens to sell.
/// @return outputAmount The amount of base tokens received.
function sellQuote(uint256 inputAmount) public view returns (uint256) {
uint256 inputAmountWithFee = inputAmount * 997;
return (inputAmountWithFee * baseTokenReserves()) / ((fractionalTokenReserves() * 1000) + inputAmountWithFee);
}
/// @notice The amount of lp tokens received for adding a given amount of base tokens and fractional tokens.
/// @dev Calculated as a share of existing deposits. If there are no existing deposits, then initializes to
/// sqrt(baseTokenAmount * fractionalTokenAmount).
/// @param baseTokenAmount The amount of base tokens to add.
/// @param fractionalTokenAmount The amount of fractional tokens to add.
/// @return lpTokenAmount The amount of lp tokens received.
function addQuote(uint256 baseTokenAmount, uint256 fractionalTokenAmount) public view returns (uint256) {
uint256 lpTokenSupply = lpToken.totalSupply();
if (lpTokenSupply > 0) {
// calculate amount of lp tokens as a fraction of existing reserves
uint256 baseTokenShare = (baseTokenAmount * lpTokenSupply) / baseTokenReserves();
uint256 fractionalTokenShare = (fractionalTokenAmount * lpTokenSupply) / fractionalTokenReserves();
return Math.min(baseTokenShare, fractionalTokenShare);
} else {
// if there is no liquidity then init
return Math.sqrt(baseTokenAmount * fractionalTokenAmount);
}
}
/// @notice The amount of base tokens and fractional tokens received for burning a given amount of lp tokens.
/// @dev Calculated as a share of existing deposits.
/// @param lpTokenAmount The amount of lp tokens to burn.
/// @return baseTokenAmount The amount of base tokens received.
/// @return fractionalTokenAmount The amount of fractional tokens received.
function removeQuote(uint256 lpTokenAmount) public view returns (uint256, uint256) {
uint256 lpTokenSupply = lpToken.totalSupply();
uint256 baseTokenOutputAmount = (baseTokenReserves() * lpTokenAmount) / lpTokenSupply;
uint256 fractionalTokenOutputAmount = (fractionalTokenReserves() * lpTokenAmount) / lpTokenSupply;
return (baseTokenOutputAmount, fractionalTokenOutputAmount);
}
// ************************ //
// Internal utils //
// ************************ //
function _transferFrom(address from, address to, uint256 amount) internal returns (bool) {
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/// @dev Validates that the given tokenIds are valid for the contract's merkle root. Reverts
/// if any of the tokenId proofs are invalid.
function _validateTokenIds(uint256[] calldata tokenIds, bytes32[][] calldata proofs) internal view {
// if merkle root is not set then all tokens are valid
if (merkleRoot == bytes23(0)) return;
// validate merkle proofs against merkle root
for (uint256 i = 0; i < tokenIds.length; i++) {
bool isValid = MerkleProofLib.verify(proofs[i], merkleRoot, keccak256(abi.encodePacked(tokenIds[i])));
require(isValid, "Invalid merkle proof");
}
}
/// @dev Returns the current base token reserves. If the base token is ETH then it ignores
/// the msg.value that is being sent in the current call context - this is to ensure the
/// xyk math is correct in the buy() and add() functions.
function _baseTokenReserves() internal view returns (uint256) {
return baseToken == address(0)
? address(this).balance - msg.value
// subtract the msg.value if the base token is ETH
: ERC20(baseToken).balanceOf(address(this));
}
} | 4,588 | 486 | 2 | 1. [H-01] Reentrancy in buy function for ERC777 tokens allows buying funds with considerable discount. (Reentrancy)
Current implementation of functions `add`, `remove`, `buy` and `sell` first transfer fractional tokens, and then base tokens.
2. [H-02] Liquidity providers may lose funds when adding liquidity (overflow)
Liquidity providers may lose a portion of provided liquidity in either of the pair tokens. While the `minLpTokenAmount` protects from slippage when adding liquidity, it doesn't protect from providing liquidity at different K. `addQuote()`
3. [H-03] First depositor can break minting of shares
In Pair.add(), the amount of LP token minted is calculated as
4. [M-01] Missing deadline checks allow pending transactions to be maliciously executed.
The Pair contract does not allow users to submit a deadline for their action. This missing feature enables pending transactions to be maliciously executed at a later point.
5. [M-04] It's possible to swap NFT token ids without fee and also attacker can wrap unwrap all the NFT token balance of the Pair contract and steal their air drops for those token ids.
Users can wrap() their NFT tokens (which id is whitelisted) and receive 1e18 fractional token or they can pay 1e18 fractional token and unwrap NFT token.
6. [M-05] Pair price may be manipulated by direct transfers (Price manipulation)
An attacker may manipulate the price of a pair by transferring tokens directly to the pair. Since the Pair contract exposes the price function, it maybe be used as a price oracle in third-party integrations. Manipulating the price of a pair may allow an attacker to steal funds from such integrations. | 6 |
106_NFTLoanFacilitator.sol | // SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.12;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {SafeTransferLib, ERC20} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {INFTLoanFacilitator} from './interfaces/INFTLoanFacilitator.sol';
import {IERC721Mintable} from './interfaces/IERC721Mintable.sol';
import {ILendTicket} from './interfaces/ILendTicket.sol';
contract NFTLoanFacilitator is Ownable, INFTLoanFacilitator {
using SafeTransferLib for ERC20;
// ==== constants ====
/**
* See {INFTLoanFacilitator-INTEREST_RATE_DECIMALS}.
* @dev lowest non-zero APR possible = (1/10^3) = 0.001 = 0.1%
*/
uint8 public constant override INTEREST_RATE_DECIMALS = 3;
/// See {INFTLoanFacilitator-SCALAR}.
uint256 public constant override SCALAR = 10 ** INTEREST_RATE_DECIMALS;
// ==== state variables ====
/// See {INFTLoanFacilitator-originationFeeRate}.
/// @dev starts at 1%
uint256 public override originationFeeRate = 10 ** (INTEREST_RATE_DECIMALS - 2);
/// See {INFTLoanFacilitator-requiredImprovementRate}.
/// @dev starts at 10%
uint256 public override requiredImprovementRate = 10 ** (INTEREST_RATE_DECIMALS - 1);
/// See {INFTLoanFacilitator-lendTicketContract}.
address public override lendTicketContract;
/// See {INFTLoanFacilitator-borrowTicketContract}.
address public override borrowTicketContract;
/// See {INFTLoanFacilitator-loanInfo}.
mapping(uint256 => Loan) public loanInfo;
/// @dev tracks loan count
uint256 private _nonce = 1;
// ==== modifiers ====
modifier notClosed(uint256 loanId) {
require(!loanInfo[loanId].closed, "NFTLoanFacilitator: loan closed");
_;
}
// ==== constructor ====
constructor(address _manager) {
transferOwnership(_manager);
}
// ==== state changing external functions ====
/// See {INFTLoanFacilitator-createLoan}.
function createLoan(
uint256 collateralTokenId,
address collateralContractAddress,
uint16 maxPerAnumInterest,
uint128 minLoanAmount,
address loanAssetContractAddress,
uint32 minDurationSeconds,
address mintBorrowTicketTo
)
external
override
returns (uint256 id)
{
require(minDurationSeconds != 0, 'NFTLoanFacilitator: 0 duration');
require(minLoanAmount != 0, 'NFTLoanFacilitator: 0 loan amount');
require(collateralContractAddress != lendTicketContract,
'NFTLoanFacilitator: cannot use tickets as collateral');
require(collateralContractAddress != borrowTicketContract,
'NFTLoanFacilitator: cannot use tickets as collateral');
IERC721(collateralContractAddress).transferFrom(msg.sender, address(this), collateralTokenId);
unchecked {
id = _nonce++;
}
Loan storage loan = loanInfo[id];
loan.loanAssetContractAddress = loanAssetContractAddress;
loan.loanAmount = minLoanAmount;
loan.collateralTokenId = collateralTokenId;
loan.collateralContractAddress = collateralContractAddress;
loan.perAnumInterestRate = maxPerAnumInterest;
loan.durationSeconds = minDurationSeconds;
IERC721Mintable(borrowTicketContract).mint(mintBorrowTicketTo, id);
emit CreateLoan(
id,
msg.sender,
collateralTokenId,
collateralContractAddress,
maxPerAnumInterest,
loanAssetContractAddress,
minLoanAmount,
minDurationSeconds
);
}
/// See {INFTLoanFacilitator-closeLoan}.
function closeLoan(uint256 loanId, address sendCollateralTo) external override notClosed(loanId) {
require(IERC721(borrowTicketContract).ownerOf(loanId) == msg.sender,
"NFTLoanFacilitator: borrow ticket holder only");
Loan storage loan = loanInfo[loanId];
require(loan.lastAccumulatedTimestamp == 0, "NFTLoanFacilitator: has lender, use repayAndCloseLoan");
loan.closed = true;
IERC721(loan.collateralContractAddress).transferFrom(address(this), sendCollateralTo, loan.collateralTokenId);
emit Close(loanId);
}
/// See {INFTLoanFacilitator-lend}.
function lend(
uint256 loanId,
uint16 interestRate,
uint128 amount,
uint32 durationSeconds,
address sendLendTicketTo
)
external
override
notClosed(loanId)
{
Loan storage loan = loanInfo[loanId];
if (loan.lastAccumulatedTimestamp == 0) {
address loanAssetContractAddress = loan.loanAssetContractAddress;
require(loanAssetContractAddress != address(0), "NFTLoanFacilitator: invalid loan");
require(interestRate <= loan.perAnumInterestRate, 'NFTLoanFacilitator: rate too high');
require(durationSeconds >= loan.durationSeconds, 'NFTLoanFacilitator: duration too low');
require(amount >= loan.loanAmount, 'NFTLoanFacilitator: amount too low');
loan.perAnumInterestRate = interestRate;
loan.lastAccumulatedTimestamp = uint40(block.timestamp);
loan.durationSeconds = durationSeconds;
loan.loanAmount = amount;
ERC20(loanAssetContractAddress).safeTransferFrom(msg.sender, address(this), amount);
uint256 facilitatorTake = amount * originationFeeRate / SCALAR;
ERC20(loanAssetContractAddress).safeTransfer(
IERC721(borrowTicketContract).ownerOf(loanId),
amount - facilitatorTake
);
IERC721Mintable(lendTicketContract).mint(sendLendTicketTo, loanId);
} else {
uint256 previousLoanAmount = loan.loanAmount;
// will underflow if amount < previousAmount
uint256 amountIncrease = amount - previousLoanAmount;
{
uint256 previousInterestRate = loan.perAnumInterestRate;
uint256 previousDurationSeconds = loan.durationSeconds;
require(interestRate <= previousInterestRate, 'NFTLoanFacilitator: rate too high');
require(durationSeconds >= previousDurationSeconds, 'NFTLoanFacilitator: duration too low');
require((previousLoanAmount * requiredImprovementRate / SCALAR) <= amountIncrease
|| previousDurationSeconds + (previousDurationSeconds * requiredImprovementRate / SCALAR) <= durationSeconds
|| (previousInterestRate != 0
&& previousInterestRate - (previousInterestRate * requiredImprovementRate / SCALAR) >= interestRate),
"NFTLoanFacilitator: proposed terms must be better than existing terms");
}
uint256 accumulatedInterest = _interestOwed(
previousLoanAmount,
loan.lastAccumulatedTimestamp,
loan.perAnumInterestRate,
loan.accumulatedInterest
);
require(accumulatedInterest <= type(uint128).max,
"NFTLoanFacilitator: accumulated interest exceeds uint128");
loan.perAnumInterestRate = interestRate;
loan.lastAccumulatedTimestamp = uint40(block.timestamp);
loan.durationSeconds = durationSeconds;
loan.loanAmount = amount;
loan.accumulatedInterest = uint128(accumulatedInterest);
address currentLoanOwner = IERC721(lendTicketContract).ownerOf(loanId);
if (amountIncrease > 0) {
address loanAssetContractAddress = loan.loanAssetContractAddress;
ERC20(loanAssetContractAddress).safeTransferFrom(
msg.sender,
address(this),
amount + accumulatedInterest
);
ERC20(loanAssetContractAddress).safeTransfer(
currentLoanOwner,
accumulatedInterest + previousLoanAmount
);
uint256 facilitatorTake = (amountIncrease * originationFeeRate / SCALAR);
ERC20(loanAssetContractAddress).safeTransfer(
IERC721(borrowTicketContract).ownerOf(loanId),
amountIncrease - facilitatorTake
);
} else {
ERC20(loan.loanAssetContractAddress).safeTransferFrom(
msg.sender,
currentLoanOwner,
accumulatedInterest + previousLoanAmount
);
}
ILendTicket(lendTicketContract).loanFacilitatorTransfer(currentLoanOwner, sendLendTicketTo, loanId);
emit BuyoutLender(loanId, msg.sender, currentLoanOwner, accumulatedInterest, previousLoanAmount);
}
emit Lend(loanId, msg.sender, interestRate, amount, durationSeconds);
}
/// See {INFTLoanFacilitator-repayAndCloseLoan}.
function repayAndCloseLoan(uint256 loanId) external override notClosed(loanId) {
Loan storage loan = loanInfo[loanId];
uint256 interest = _interestOwed(
loan.loanAmount,
loan.lastAccumulatedTimestamp,
loan.perAnumInterestRate,
loan.accumulatedInterest
);
address lender = IERC721(lendTicketContract).ownerOf(loanId);
loan.closed = true;
ERC20(loan.loanAssetContractAddress).safeTransferFrom(msg.sender, lender, interest + loan.loanAmount);
IERC721(loan.collateralContractAddress).safeTransferFrom(
address(this),
IERC721(borrowTicketContract).ownerOf(loanId),
loan.collateralTokenId
);
emit Repay(loanId, msg.sender, lender, interest, loan.loanAmount);
emit Close(loanId);
}
/// See {INFTLoanFacilitator-seizeCollateral}.
function seizeCollateral(uint256 loanId, address sendCollateralTo) external override notClosed(loanId) {
require(IERC721(lendTicketContract).ownerOf(loanId) == msg.sender,
"NFTLoanFacilitator: lend ticket holder only");
Loan storage loan = loanInfo[loanId];
require(block.timestamp > loan.durationSeconds + loan.lastAccumulatedTimestamp,
"NFTLoanFacilitator: payment is not late");
loan.closed = true;
IERC721(loan.collateralContractAddress).safeTransferFrom(
address(this),
sendCollateralTo,
loan.collateralTokenId
);
emit SeizeCollateral(loanId);
emit Close(loanId);
}
// === owner state changing ===
/**
* @notice Sets lendTicketContract to _contract
* @dev cannot be set if lendTicketContract is already set
*/
function setLendTicketContract(address _contract) external onlyOwner {
require(lendTicketContract == address(0), 'NFTLoanFacilitator: already set');
lendTicketContract = _contract;
}
/**
* @notice Sets borrowTicketContract to _contract
* @dev cannot be set if borrowTicketContract is already set
*/
function setBorrowTicketContract(address _contract) external onlyOwner {
require(borrowTicketContract == address(0), 'NFTLoanFacilitator: already set');
borrowTicketContract = _contract;
}
/// @notice Transfers `amount` of loan origination fees for `asset` to `to`
function withdrawOriginationFees(address asset, uint256 amount, address to) external onlyOwner {
ERC20(asset).safeTransfer(to, amount);
emit WithdrawOriginationFees(asset, amount, to);
}
/**
* @notice Updates originationFeeRate the faciliator keeps of each loan amount
* @dev Cannot be set higher than 5%
*/
function updateOriginationFeeRate(uint32 _originationFeeRate) external onlyOwner {
require(_originationFeeRate <= 5 * (10 ** (INTEREST_RATE_DECIMALS - 2)), "NFTLoanFacilitator: max fee 5%");
originationFeeRate = _originationFeeRate;
emit UpdateOriginationFeeRate(_originationFeeRate);
}
/**
* @notice updates the percent improvement required of at least one loan term when buying out lender
* a loan that already has a lender. E.g. setting this value to 10 means duration or amount
* must be 10% higher or interest rate must be 10% lower.
* @dev Cannot be 0.
*/
function updateRequiredImprovementRate(uint256 _improvementRate) external onlyOwner {
require(_improvementRate > 0, 'NFTLoanFacilitator: 0 improvement rate');
requiredImprovementRate = _improvementRate;
emit UpdateRequiredImprovementRate(_improvementRate);
}
// ==== external view ====
/// See {INFTLoanFacilitator-loanInfoStruct}.
function loanInfoStruct(uint256 loanId) external view override returns (Loan memory) {
return loanInfo[loanId];
}
/// See {INFTLoanFacilitator-totalOwed}.
function totalOwed(uint256 loanId) external view override returns (uint256) {
Loan storage loan = loanInfo[loanId];
if (loan.closed || loan.lastAccumulatedTimestamp == 0) return 0;
return loanInfo[loanId].loanAmount + _interestOwed(
loan.loanAmount,
loan.lastAccumulatedTimestamp,
loan.perAnumInterestRate,
loan.accumulatedInterest
);
}
/// See {INFTLoanFacilitator-interestOwed}.
function interestOwed(uint256 loanId) external view override returns (uint256) {
Loan storage loan = loanInfo[loanId];
if(loan.closed || loan.lastAccumulatedTimestamp == 0) return 0;
return _interestOwed(
loan.loanAmount,
loan.lastAccumulatedTimestamp,
loan.perAnumInterestRate,
loan.accumulatedInterest
);
}
/// See {INFTLoanFacilitator-loanEndSeconds}.
function loanEndSeconds(uint256 loanId) external view override returns (uint256) {
Loan storage loan = loanInfo[loanId];
return loan.durationSeconds + loan.lastAccumulatedTimestamp;
}
// === private ===
/// @dev Returns the total interest owed on loan
function _interestOwed(
uint256 loanAmount,
uint256 lastAccumulatedTimestamp,
uint256 perAnumInterestRate,
uint256 accumulatedInterest
)
internal
view
returns (uint256)
{
return loanAmount
* (block.timestamp - lastAccumulatedTimestamp)
* (perAnumInterestRate * 1e18 / 365 days)
/ 1e21
+ accumulatedInterest;
}
} | 3,338 | 389 | 2 | 1. [H-01] Can force borrower to pay huge interest.
The loan amount is used as a min loan amount. It can be matched as high as possible (realistically up to the collateral NFT's worth to remain in profit) and the borrower has to pay interest on the entire amount instead of just on the desired loan amount when the loan was created.
`require(amount >= loan.loanAmount, 'NFTLoanFacilitator: amount too low’);` in `lend()` function.
2. [H-02] currentLoanOwner can manipulate loanInfo when any lenders try to buyout. (Reentrancy)
If an attacker already calls `lend()` to lend to a loan, the attacker can manipulate loanInfo by reentrancy attack when any lenders try to buyout. The attacker can set bad values of lendInfo (e.g. very long duration, and 0 interest rate) that the lender who wants to buyout don't expect.
3. [H-03] Borrower can be their own lender and steal funds from buyout due to reentrancy. (Reentrancy)
`lend()` function. If borrower lends their own loan, they can repay and close the loan before ownership of the lend ticket is transferred to the new lender. The borrower will keep the NFT + loan amount + accrued interest.
4. [M-01] When an attacker lends to a loan, the attacker can trigger DoS that any lenders can not buyout it. (DoS)
`lend()` function
5. M-02: Protocol doesn't handle fee on transfer tokens. L155
`lend()` function
6. M-03: sendCollateralTo is unchecked in closeLoan(), which can cause user's collateral NFT to be frozen. L116
`closeLoan()` function
7. [M-04] `requiredImprovementRate` can not work as expected when `previousInterestRate` less than 10 due to precision loss
8. M-05: Borrowers lose funds if they call `repayAndCloseLoan` instead of `closeLoan`. (Potential for Loss of Funds)
9. M-06: Might not get desired min loan amount if `_originationFeeRate` changes
10. M-07: `mintBorrowTicketTo` can be a contract with no `onERC721Received` method, which may cause the BorrowTicket NFT to be frozen and put users' funds at risk | 9 |
36_Auction.sol | pragma solidity =0.8.7;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import './interfaces/IFactory.sol';
import './interfaces/IBasket.sol';
import "./interfaces/IAuction.sol";
import "hardhat/console.sol";
contract Auction is IAuction {
using SafeERC20 for IERC20;
uint256 private constant BASE = 1e18;
uint256 private constant ONE_DAY = 4 * 60 * 24;
uint256 private constant BLOCK_DECREMENT = 10000;
bool public override auctionOngoing;
uint256 public override auctionStart;
bool public override hasBonded;
uint256 public override bondAmount;
uint256 public override bondTimestamp;
bool public override initialized;
IBasket public override basket;
IFactory public override factory;
address public override auctionBonder;
Bounty[] private _bounties;
modifier onlyBasket() {
require(msg.sender == address(basket), 'not basket');
_;
}
function startAuction() onlyBasket public override {
require(auctionOngoing == false, 'ongoing auction');
auctionOngoing = true;
auctionStart = block.number;
emit AuctionStarted();
}
function killAuction() onlyBasket public override {
auctionOngoing = false;
}
function initialize(address basket_, address factory_) public override {
require(!initialized);
basket = IBasket(basket_);
factory = IFactory(factory_);
initialized = true;
}
function bondForRebalance() public override {
require(auctionOngoing);
require(!hasBonded);
bondTimestamp = block.number;
IERC20 basketToken = IERC20(address(basket));
bondAmount = basketToken.totalSupply() / factory.bondPercentDiv();
basketToken.safeTransferFrom(msg.sender, address(this), bondAmount);
hasBonded = true;
auctionBonder = msg.sender;
emit Bonded(msg.sender, bondAmount);
}
function settleAuction(
uint256[] memory bountyIDs,
address[] memory inputTokens,
uint256[] memory inputWeights,
address[] memory outputTokens,
uint256[] memory outputWeights
) public override {
require(auctionOngoing);
require(hasBonded);
require(bondTimestamp + ONE_DAY > block.number);
require(msg.sender == auctionBonder);
for (uint256 i = 0; i < inputTokens.length; i++) {
IERC20(inputTokens[i]).safeTransferFrom(msg.sender, address(basket), inputWeights[i]);
}
for (uint256 i = 0; i < outputTokens.length; i++) {
IERC20(outputTokens[i]).safeTransferFrom(address(basket), msg.sender, outputWeights[i]);
}
uint256 a = factory.auctionMultiplier() * basket.ibRatio();
uint256 b = (bondTimestamp - auctionStart) * BASE / factory.auctionDecrement();
uint256 newRatio = a - b;
(address[] memory pendingTokens, uint256[] memory pendingWeights) = basket.getPendingWeights();
IERC20 basketAsERC20 = IERC20(address(basket));
for (uint256 i = 0; i < pendingWeights.length; i++) {
uint256 tokensNeeded = basketAsERC20.totalSupply() * pendingWeights[i] * newRatio / BASE / BASE;
require(IERC20(pendingTokens[i]).balanceOf(address(basket)) >= tokensNeeded);
}
basketAsERC20.transfer(msg.sender, bondAmount);
withdrawBounty(bountyIDs);
basket.setNewWeights();
basket.updateIBRatio(newRatio);
auctionOngoing = false;
hasBonded = false;
emit AuctionSettled(msg.sender);
}
function bondBurn() external override {
require(auctionOngoing);
require(hasBonded);
require(bondTimestamp + ONE_DAY <= block.number);
basket.auctionBurn(bondAmount);
hasBonded = false;
auctionOngoing = false;
basket.deleteNewIndex();
emit BondBurned(msg.sender, auctionBonder, bondAmount);
auctionBonder = address(0);
}
function addBounty(IERC20 token, uint256 amount) public override returns (uint256) {
// add bounty to basket
token.safeTransferFrom(msg.sender, address(this), amount);
_bounties.push(Bounty({
token: address(token),
amount: amount,
active: true
}));
uint256 id = _bounties.length - 1;
emit BountyAdded(token, amount, id);
return id;
}
function withdrawBounty(uint256[] memory bountyIds) internal {
// withdraw bounties
for (uint256 i = 0; i < bountyIds.length; i++) {
Bounty memory bounty = _bounties[bountyIds[i]];
require(bounty.active);
IERC20(bounty.token).transfer(msg.sender, bounty.amount);
bounty.active = false;
emit BountyClaimed(msg.sender, bounty.token, bounty.amount, bountyIds[i]);
}
}
} | 1,101 | 152 | 2 | 1. [H-01] Re-entrancy in settleAuction allow stealing all funds (reentrancy)
Function `settleAuction()`
2. M-01: Use safeTransfer instead of `transfer`.
3. M-03: `onlyOwner` Role Can Unintentionally Influence `settleAuction()`. (Centralization risks)
4. M-07: No minimum rate in the auction may break the protocol under network failure
The aution contract decides a new ibRatio in the function `settleAuction`
5. M-08: `settleAuction` may be impossible if locked at a wrong time. (`Timestamp manipulation`)
The contract uses `block.number` for the `bondTimestamp` and `settlement` mechanisms
6. M-11: Owner can steal all Basket funds during auction
The owner of Factory contract can modify the values of auctionMultiplier and auctionDecrement at any time
7. M-15: Auction.sol#settleAuction() late auction bond could potentially not being able to be settled, cause funds loss to bonder
8. M-16: Auction.sol#settleAuction() Mishandling bounty state could potentially disrupt settleAuction()
9. M-17: Scoop ERC20 tokens from basket contract L69
10. M-22: Incorrect data location specifier can be abused to cause DoS and fund loss. L143 | 9 |
17_PnL.sol | // SPDX-License-Identifier: AGPLv3
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IPnL.sol";
import "../common/Controllable.sol";
import "../interfaces/IPnL.sol";
import "../common/Constants.sol";
import {FixedGTokens} from "../common/FixedContracts.sol";
/// @notice Contract for calculating protocol profit and loss. The PnL contract stores snapshots
/// of total assets in pwrd and gvt, which are used to calculate utilisation ratio and establish
/// changes in underling pwrd and gvt factors. The protocol will allow these values to drift as long
/// as they stay within a certain threshold of protocol actuals, or large amounts of assets are being
/// deposited or withdrawn from the protocol. The PnL contract ensures that any profits are distributed
/// between pwrd and gvt based on the utilisation ratio - as this ratio movese towards 1, a larger
/// amount of the pwrd profit is shifted to gvt. Protocol losses are on the other hand soaked up
/// by gvt, ensuring that pwrd never lose value.
///
/// ###############################################
/// PnL variables and calculations
/// ###############################################
///
/// yield - system gains and losses from assets invested into strategies are realised once
/// a harvest is run. Yield is ditributed to pwrd and gvt based on the utilisation ratio of the
/// two tokens (see _calcProfit).
///
/// PerformanceFee - The performance fee is deducted from any yield profits, and is used to
/// buy back and distribute governance tokens to users.
///
/// hodler Fee - Withdrawals experience a hodler fee that is socialized to all other holders.
/// Like other gains, this isn't realised on withdrawal, but rather when a critical amount
/// has amassed in the system (totalAssetsPercentThreshold).
///
/// ###############################################
/// PnL Actions
/// ###############################################
///
/// Pnl has two trigger mechanisms:
/// - Harvest:
/// - It will realize any loss/profit from the strategy
/// - It will atempt to update lastest cached curve stable coin dy
/// - if successfull, it will try to realize any price changes (pre tvl vs current)
/// - Withdrawals
/// - Any user withdrawals are distributing the holder fee to the other users
contract PnL is Controllable, Constants, FixedGTokens, IPnL {
using SafeMath for uint256;
uint256 public override lastGvtAssets;
uint256 public override lastPwrdAssets;
bool public rebase = true;
uint256 public performanceFee;
// Amount of gains to use to buy back and distribute gov tokens
event LogRebaseSwitch(bool status);
event LogNewPerfromanceFee(uint256 fee);
event LogNewGtokenChange(bool pwrd, int256 change);
event LogPnLExecution(
uint256 deductedAssets,
int256 totalPnL,
int256 investPnL,
int256 pricePnL,
uint256 withdrawalBonus,
uint256 performanceBonus,
uint256 beforeGvtAssets,
uint256 beforePwrdAssets,
uint256 afterGvtAssets,
uint256 afterPwrdAssets
);
constructor(
address pwrd,
address gvt,
uint256 pwrdAssets,
uint256 gvtAssets
) public FixedGTokens(pwrd, gvt) {
lastPwrdAssets = pwrdAssets;
lastGvtAssets = gvtAssets;
}
/// @notice Turn pwrd rebasing on/off - This stops yield/ hodler bonuses to be distributed to the pwrd
/// token, which effectively stops it from rebasing any further.
function setRebase(bool _rebase) external onlyOwner {
rebase = _rebase;
emit LogRebaseSwitch(_rebase);
}
/// @notice Fee taken from gains to be redistributed to users who stake their tokens
/// @param _performanceFee Amount to remove from gains (%BP)
function setPerformanceFee(uint256 _performanceFee) external onlyOwner {
performanceFee = _performanceFee;
emit LogNewPerfromanceFee(_performanceFee);
}
/// @notice Increase previously recorded GToken assets by specific amount
/// @param pwrd pwrd/gvt
/// @param dollarAmount Amount to increase by
function increaseGTokenLastAmount(bool pwrd, uint256 dollarAmount) external override {
require(msg.sender == controller, "increaseGTokenLastAmount: !controller");
if (!pwrd) {
lastGvtAssets = lastGvtAssets.add(dollarAmount);
} else {
lastPwrdAssets = lastPwrdAssets.add(dollarAmount);
}
emit LogNewGtokenChange(pwrd, int256(dollarAmount));
}
/// @notice Decrease previously recorded GToken assets by specific amount
/// @param pwrd pwrd/gvt
/// @param dollarAmount Amount to decrease by
/// @param bonus hodler bonus
function decreaseGTokenLastAmount(
bool pwrd,
uint256 dollarAmount,
uint256 bonus
) external override {
require(msg.sender == controller, "decreaseGTokenLastAmount: !controller");
uint256 lastGA = lastGvtAssets;
uint256 lastPA = lastPwrdAssets;
if (!pwrd) {
lastGA = dollarAmount > lastGA ? 0 : lastGA.sub(dollarAmount);
} else {
lastPA = dollarAmount > lastPA ? 0 : lastPA.sub(dollarAmount);
}
if (bonus > 0) {
uint256 preGABeforeBonus = lastGA;
uint256 prePABeforeBonus = lastPA;
uint256 preTABeforeBonus = preGABeforeBonus.add(prePABeforeBonus);
if (rebase) {
lastGA = preGABeforeBonus.add(bonus.mul(preGABeforeBonus).div(preTABeforeBonus));
lastPA = prePABeforeBonus.add(bonus.mul(prePABeforeBonus).div(preTABeforeBonus));
} else {
lastGA = preGABeforeBonus.add(bonus);
}
emit LogPnLExecution(0, int256(bonus), 0, 0, bonus, 0, preGABeforeBonus, prePABeforeBonus, lastGA, lastPA);
}
lastGvtAssets = lastGA;
lastPwrdAssets = lastPA;
emit LogNewGtokenChange(pwrd, int256(-dollarAmount));
}
/// @notice Return latest system asset states
function calcPnL() external view override returns (uint256, uint256) {
return (lastGvtAssets, lastPwrdAssets);
}
/// @notice Calculate utilisation ratio between gvt and pwrd
function utilisationRatio() external view override returns (uint256) {
return lastGvtAssets != 0 ? lastPwrdAssets.mul(PERCENTAGE_DECIMAL_FACTOR).div(lastGvtAssets) : 0;
}
/// @notice Update assets after entering emergency state
function emergencyPnL() external override {
require(msg.sender == controller, "emergencyPnL: !controller");
forceDistribute();
}
/// @notice Recover system from emergency state
function recover() external override {
require(msg.sender == controller, "recover: !controller");
forceDistribute();
}
/// @notice Distribute yield based on utilisation ratio
/// @param gvtAssets Total gvt assets
/// @param pwrdAssets Total pwrd assets
/// @param profit Amount of profit to distribute
/// @param reward Rewards contract
function handleInvestGain(
uint256 gvtAssets,
uint256 pwrdAssets,
uint256 profit,
address reward
)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 performanceBonus;
if (performanceFee > 0 && reward != address(0)) {
performanceBonus = profit.mul(performanceFee).div(PERCENTAGE_DECIMAL_FACTOR);
profit = profit.sub(performanceBonus);
}
if (rebase) {
uint256 totalAssets = gvtAssets.add(pwrdAssets);
uint256 gvtProfit = profit.mul(gvtAssets).div(totalAssets);
uint256 pwrdProfit = profit.mul(pwrdAssets).div(totalAssets);
uint256 factor = pwrdAssets.mul(10000).div(gvtAssets);
if (factor > 10000) factor = 10000;
if (factor < 8000) {
factor = factor.mul(3).div(8).add(3000);
} else {
factor = factor.sub(8000).mul(2).add(6000);
}
uint256 portionFromPwrdProfit = pwrdProfit.mul(factor).div(10000);
gvtAssets = gvtAssets.add(gvtProfit.add(portionFromPwrdProfit));
pwrdAssets = pwrdAssets.add(pwrdProfit.sub(portionFromPwrdProfit));
} else {
gvtAssets = gvtAssets.add(profit);
}
return (gvtAssets, pwrdAssets, performanceBonus);
}
/// @notice Distribute losses
/// @param gvtAssets Total gvt assets
/// @param pwrdAssets Total pwrd assets
/// @param loss Amount of loss to distribute
function handleLoss(
uint256 gvtAssets,
uint256 pwrdAssets,
uint256 loss
) private pure returns (uint256, uint256) {
uint256 maxGvtLoss = gvtAssets.sub(DEFAULT_DECIMALS_FACTOR);
if (loss > maxGvtLoss) {
gvtAssets = DEFAULT_DECIMALS_FACTOR;
pwrdAssets = pwrdAssets.sub(loss.sub(maxGvtLoss));
} else {
gvtAssets = gvtAssets - loss;
}
return (gvtAssets, pwrdAssets);
}
function forceDistribute() private {
uint256 total = _controller().totalAssets();
if (total > lastPwrdAssets.add(DEFAULT_DECIMALS_FACTOR)) {
lastGvtAssets = total - lastPwrdAssets;
} else {
lastGvtAssets = DEFAULT_DECIMALS_FACTOR;
lastPwrdAssets = total.sub(DEFAULT_DECIMALS_FACTOR);
}
}
function distributeStrategyGainLoss(
uint256 gain,
uint256 loss,
address reward
) external override {
require(msg.sender == controller, "!Controller");
uint256 lastGA = lastGvtAssets;
uint256 lastPA = lastPwrdAssets;
uint256 performanceBonus;
uint256 gvtAssets;
uint256 pwrdAssets;
int256 investPnL;
if (gain > 0) {
(gvtAssets, pwrdAssets, performanceBonus) = handleInvestGain(lastGA, lastPA, gain, reward);
if (performanceBonus > 0) {
gvt.mint(reward, gvt.factor(gvtAssets), performanceBonus);
gvtAssets = gvtAssets.add(performanceBonus);
}
lastGvtAssets = gvtAssets;
lastPwrdAssets = pwrdAssets;
investPnL = int256(gain);
} else if (loss > 0) {
(lastGvtAssets, lastPwrdAssets) = handleLoss(lastGA, lastPA, loss);
investPnL = -int256(loss);
}
emit LogPnLExecution(
0,
investPnL,
investPnL,
0,
0,
performanceBonus,
lastGA,
lastPA,
lastGvtAssets,
lastPwrdAssets
);
}
function distributePriceChange(uint256 currentTotalAssets) external override {
require(msg.sender == controller, "!Controller");
uint256 gvtAssets = lastGvtAssets;
uint256 pwrdAssets = lastPwrdAssets;
uint256 totalAssets = gvtAssets.add(pwrdAssets);
if (currentTotalAssets > totalAssets) {
lastGvtAssets = gvtAssets.add(currentTotalAssets.sub(totalAssets));
} else if (currentTotalAssets < totalAssets) {
(lastGvtAssets, lastPwrdAssets) = handleLoss(gvtAssets, pwrdAssets, totalAssets.sub(currentTotalAssets));
}
int256 priceChange = int256(currentTotalAssets) - int256(totalAssets);
emit LogPnLExecution(
0,
priceChange,
0,
priceChange,
0,
0,
gvtAssets,
pwrdAssets,
lastGvtAssets,
lastPwrdAssets
);
}
} | 2,827 | 310 | 1 | 1. [H-01] implicit underflows. (underflow)
`function decreaseGTokenLastAmount(bool pwrd, uint256 dollarAmount, uint256 bonus).`
2. [H-03] Incorrect use of operator leads to arbitrary minting of GVT tokens.
function `distributeStrategyGainLoss()` | 2 |
74_TimeswapPair.sol | // SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IPair} from './interfaces/IPair.sol';
import {IFactory} from './interfaces/IFactory.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {MintMath} from './libraries/MintMath.sol';
import {BurnMath} from './libraries/BurnMath.sol';
import {LendMath} from './libraries/LendMath.sol';
import {WithdrawMath} from './libraries/WithdrawMath.sol';
import {BorrowMath} from './libraries/BorrowMath.sol';
import {PayMath} from './libraries/PayMath.sol';
import {SafeTransfer} from './libraries/SafeTransfer.sol';
import {Array} from './libraries/Array.sol';
import {Callback} from './libraries/Callback.sol';
import {BlockNumber} from './libraries/BlockNumber.sol';
/// @title Timeswap Pair
/// @author Timeswap Labs
/// @notice It is recommnded to use Timeswap Convenience to interact with this contract.
/// @notice All error messages are coded and can be found in the documentation.
contract TimeswapPair is IPair {
using SafeTransfer for IERC20;
using Array for Due[];
/* ===== MODEL ===== */
/// @inheritdoc IPair
IFactory public immutable override factory;
/// @inheritdoc IPair
IERC20 public immutable override asset;
/// @inheritdoc IPair
IERC20 public immutable override collateral;
/// @inheritdoc IPair
uint16 public immutable override fee;
/// @inheritdoc IPair
uint16 public immutable override protocolFee;
/// @dev Stores the individual states of each Pool.
mapping(uint256 => Pool) private pools;
/// @dev Stores the access state for reentrancy guard.
uint256 private locked;
/* ===== VIEW =====*/
/// @inheritdoc IPair
function constantProduct(uint256 maturity)
external
view
override
returns (
uint112 x,
uint112 y,
uint112 z
)
{
State memory state = pools[maturity].state;
return (state.x, state.y, state.z);
}
/// @inheritdoc IPair
function totalReserves(uint256 maturity) external view override returns (Tokens memory) {
return pools[maturity].state.reserves;
}
/// @inheritdoc IPair
function totalLiquidity(uint256 maturity) external view override returns (uint256) {
return pools[maturity].state.totalLiquidity;
}
/// @inheritdoc IPair
function liquidityOf(uint256 maturity, address owner) external view override returns (uint256) {
return pools[maturity].liquidities[owner];
}
/// @inheritdoc IPair
function totalClaims(uint256 maturity) external view override returns (Claims memory) {
return pools[maturity].state.totalClaims;
}
/// @inheritdoc IPair
function claimsOf(uint256 maturity, address owner) external view override returns (Claims memory) {
return pools[maturity].claims[owner];
}
/// @inheritdoc IPair
function totalDebtCreated(uint256 maturity) external view override returns (uint120) {
return pools[maturity].state.totalDebtCreated;
}
/// @inheritdoc IPair
function dueOf(uint256 maturity, address owner, uint256 id) external view override returns (Due memory) {
return pools[maturity].dues[owner][id];
}
/* ===== INIT ===== */
/// @dev Initializes the Pair contract.
/// @dev Called by the Timeswap factory contract.
/// @param _asset The address of the ERC20 being lent and borrowed.
/// @param _collateral The address of the ERC20 as the collateral.
/// @param _fee The chosen fee rate.
/// @param _protocolFee The chosen protocol fee rate.
constructor(
IERC20 _asset,
IERC20 _collateral,
uint16 _fee,
uint16 _protocolFee
) {
factory = IFactory(msg.sender);
asset = _asset;
collateral = _collateral;
fee = _fee;
protocolFee = _protocolFee;
}
/* ===== MODIFIER ===== */
/// @dev The modifier for reentrancy guard.
modifier lock() {
require(locked == 0, 'E211');
locked = 1;
_;
locked = 0;
}
/* ===== UPDATE ===== */
/// @inheritdoc IPair
function mint(
uint256 maturity,
address liquidityTo,
address dueTo,
uint112 xIncrease,
uint112 yIncrease,
uint112 zIncrease,
bytes calldata data
)
external
override
lock
returns (
uint256 liquidityOut,
uint256 id,
Due memory dueOut
)
{
require(block.timestamp < maturity, 'E202');
require(maturity - block.timestamp < 0x100000000, 'E208');
require(liquidityTo != address(0) && dueTo != address(0), 'E201');
require(liquidityTo != address(this) && dueTo != address(this), 'E204');
require(xIncrease > 0 && yIncrease > 0 && zIncrease > 0, 'E205');
Pool storage pool = pools[maturity];
if (pool.state.totalLiquidity == 0) {
uint256 liquidityTotal = MintMath.getLiquidityTotal(xIncrease);
liquidityOut = MintMath.getLiquidity(maturity, liquidityTotal, protocolFee);
pool.state.totalLiquidity += liquidityTotal;
pool.liquidities[factory.owner()] += liquidityTotal - liquidityOut;
} else {
uint256 liquidityTotal = MintMath.getLiquidityTotal(pool.state, xIncrease, yIncrease, zIncrease);
liquidityOut = MintMath.getLiquidity(maturity, liquidityTotal, protocolFee);
pool.state.totalLiquidity += liquidityTotal;
pool.liquidities[factory.owner()] += liquidityTotal - liquidityOut;
}
require(liquidityOut > 0, 'E212');
pool.liquidities[liquidityTo] += liquidityOut;
dueOut.debt = MintMath.getDebt(maturity, xIncrease, yIncrease);
dueOut.collateral = MintMath.getCollateral(maturity, zIncrease);
dueOut.startBlock = BlockNumber.get();
Callback.mint(asset, collateral, xIncrease, dueOut.collateral, data);
id = pool.dues[dueTo].insert(dueOut);
pool.state.reserves.asset += xIncrease;
pool.state.reserves.collateral += dueOut.collateral;
pool.state.totalDebtCreated += dueOut.debt;
pool.state.x += xIncrease;
pool.state.y += yIncrease;
pool.state.z += zIncrease;
emit Sync(maturity, pool.state.x, pool.state.y, pool.state.z);
emit Mint(maturity, msg.sender, liquidityTo, dueTo, xIncrease, liquidityOut, id, dueOut);
}
/// @inheritdoc IPair
function burn(
uint256 maturity,
address assetTo,
address collateralTo,
uint256 liquidityIn
) external override lock returns (Tokens memory tokensOut) {
require(block.timestamp >= maturity, 'E203');
require(assetTo != address(0) && collateralTo != address(0), 'E201');
require(assetTo != address(this) && collateralTo != address(this), 'E204');
require(liquidityIn > 0, 'E205');
Pool storage pool = pools[maturity];
tokensOut.asset = BurnMath.getAsset(pool.state, liquidityIn);
tokensOut.collateral = BurnMath.getCollateral(pool.state, liquidityIn);
pool.state.totalLiquidity -= liquidityIn;
pool.liquidities[msg.sender] -= liquidityIn;
pool.state.reserves.asset -= tokensOut.asset;
pool.state.reserves.collateral -= tokensOut.collateral;
if (tokensOut.asset > 0) asset.safeTransfer(assetTo, tokensOut.asset);
if (tokensOut.collateral > 0) collateral.safeTransfer(collateralTo, tokensOut.collateral);
emit Burn(maturity, msg.sender, assetTo, collateralTo, liquidityIn, tokensOut);
}
/// @inheritdoc IPair
function lend(
uint256 maturity,
address bondTo,
address insuranceTo,
uint112 xIncrease,
uint112 yDecrease,
uint112 zDecrease,
bytes calldata data
) external override lock returns (Claims memory claimsOut) {
require(block.timestamp < maturity, 'E202');
require(bondTo != address(0) && insuranceTo != address(0), 'E201');
require(bondTo != address(this) && insuranceTo != address(this), 'E204');
require(xIncrease > 0, 'E205');
Pool storage pool = pools[maturity];
require(pool.state.totalLiquidity > 0, 'E206');
LendMath.check(pool.state, xIncrease, yDecrease, zDecrease, fee);
claimsOut.bond = LendMath.getBond(maturity, xIncrease, yDecrease);
claimsOut.insurance = LendMath.getInsurance(maturity, pool.state, xIncrease, zDecrease);
Callback.lend(asset, xIncrease, data);
pool.state.totalClaims.bond += claimsOut.bond;
pool.state.totalClaims.insurance += claimsOut.insurance;
pool.claims[bondTo].bond += claimsOut.bond;
pool.claims[insuranceTo].insurance += claimsOut.insurance;
pool.state.reserves.asset += xIncrease;
pool.state.x += xIncrease;
pool.state.y -= yDecrease;
pool.state.z -= zDecrease;
emit Sync(maturity, pool.state.x, pool.state.y, pool.state.z);
emit Lend(maturity, msg.sender, bondTo, insuranceTo, xIncrease, claimsOut);
}
/// @inheritdoc IPair
function withdraw(
uint256 maturity,
address assetTo,
address collateralTo,
Claims memory claimsIn
) external override lock returns (Tokens memory tokensOut) {
require(block.timestamp >= maturity, 'E203');
require(assetTo != address(0) && collateralTo != address(0), 'E201');
require(assetTo != address(this) && collateralTo != address(this), 'E204');
require(claimsIn.bond > 0 || claimsIn.insurance > 0, 'E205');
Pool storage pool = pools[maturity];
tokensOut.asset = WithdrawMath.getAsset(pool.state, claimsIn.bond);
tokensOut.collateral = WithdrawMath.getCollateral(pool.state, claimsIn.insurance);
pool.state.totalClaims.bond -= claimsIn.bond;
pool.state.totalClaims.insurance -= claimsIn.insurance;
Claims storage sender = pool.claims[msg.sender];
sender.bond -= claimsIn.bond;
sender.insurance -= claimsIn.insurance;
pool.state.reserves.asset -= tokensOut.asset;
pool.state.reserves.collateral -= tokensOut.collateral;
if (tokensOut.asset > 0) asset.safeTransfer(assetTo, tokensOut.asset);
if (tokensOut.collateral > 0) collateral.safeTransfer(collateralTo, tokensOut.collateral);
emit Withdraw(maturity, msg.sender, assetTo, collateralTo, claimsIn, tokensOut);
}
/// @inheritdoc IPair
function borrow(
uint256 maturity,
address assetTo,
address dueTo,
uint112 xDecrease,
uint112 yIncrease,
uint112 zIncrease,
bytes calldata data
) external override lock returns (uint256 id, Due memory dueOut) {
require(block.timestamp < maturity, 'E202');
require(assetTo != address(0) && dueTo != address(0), 'E201');
require(assetTo != address(this) && dueTo != address(this), 'E204');
require(xDecrease > 0, 'E205');
Pool storage pool = pools[maturity];
require(pool.state.totalLiquidity > 0, 'E206');
BorrowMath.check(pool.state, xDecrease, yIncrease, zIncrease, fee);
dueOut.debt = BorrowMath.getDebt(maturity, xDecrease, yIncrease);
dueOut.collateral = BorrowMath.getCollateral(maturity, pool.state, xDecrease, zIncrease);
dueOut.startBlock = BlockNumber.get();
Callback.borrow(collateral, dueOut.collateral, data);
id = pool.dues[dueTo].insert(dueOut);
pool.state.reserves.asset -= xDecrease;
pool.state.reserves.collateral += dueOut.collateral;
pool.state.totalDebtCreated += dueOut.debt;
pool.state.x -= xDecrease;
pool.state.y += yIncrease;
pool.state.z += zIncrease;
asset.safeTransfer(assetTo, xDecrease);
emit Sync(maturity, pool.state.x, pool.state.y, pool.state.z);
emit Borrow(maturity, msg.sender, assetTo, dueTo, xDecrease, id, dueOut);
}
/// @inheritdoc IPair
function pay(
uint256 maturity,
address to,
address owner,
uint256[] memory ids,
uint112[] memory assetsIn,
uint112[] memory collateralsOut,
bytes calldata data
) external override lock returns (uint128 assetIn, uint128 collateralOut) {
require(block.timestamp < maturity, 'E202');
require(ids.length == assetsIn.length && ids.length == collateralsOut.length, 'E205');
require(to != address(0), 'E201');
require(to != address(this), 'E204');
Pool storage pool = pools[maturity];
Due[] storage dues = pool.dues[owner];
for (uint256 i; i < ids.length; i++) {
Due storage due = dues[ids[i]];
require(due.startBlock != BlockNumber.get(), 'E207');
if (owner != msg.sender) require(collateralsOut[i] == 0, 'E213');
PayMath.checkProportional(assetsIn[i], collateralsOut[i], due);
due.debt -= assetsIn[i];
due.collateral -= collateralsOut[i];
assetIn += assetsIn[i];
collateralOut += collateralsOut[i];
}
if (assetIn > 0) Callback.pay(asset, assetIn, data);
pool.state.reserves.asset += assetIn;
pool.state.reserves.collateral -= collateralOut;
if (collateralOut > 0) collateral.safeTransfer(to, collateralOut);
emit Pay(maturity, msg.sender, to, owner, ids, assetsIn, collateralsOut, assetIn, collateralOut);
}
} | 3,200 | 379 | 2 | 1. [H-01] TimeswapPair.sol#borrow() Improper implementation allows attacker to increase pool.state.z to a large value (overflow)
n the current implementation, borrow() takes a user input value of zIncrease, while the actual collateral asset transferred in is calculated at L319, the state of pool.state.z still increased by the value of the user's input at L332.
2. [H-03] Manipulation of the Y State Results in Interest Rate Manipulation
Due to lack of constraints on user input in the TimeswapPair.sol#mint function, an attacker can arbitrarily modify the interest rate while only paying a minimal amount of Asset Token and Collateral Token.
3. [H-04] Important state updates are made after the callback in the mint() function (Callback functions)
In TimeswapPair.sol, the `mint()` function has a callback in the middle of the function while there are still updates to state that take place after the callback.
4. [H-05] In the `lend()` function state updates are made after the callback (Callback functions)
In TimeswapPair.sol, the lend() function has a callback to the msg.sender in the middle of the function while there are still updates to state that take place after the callback.
5. [H-06] borrow() function has state updates after a callback to msg.sender (Callback functions)
In TimeswapPair.sol, the borrow() function has a callback to the msg.sender in the middle of the function while there are still updates to state that take place after the callback.
6. [H-07] `pay()` function has callback to msg.sender before important state updates (Callback functions)
In TimeswapPair.sol, the pay() function has a callback to the msg.sender in the middle of the function while there are still updates to state that take place after the callback.
7. [M-06] TimeswapPair.sol#`mint()` Malicious user/attacker can mint new liquidity with an extremely small amount of yIncrease and malfunction the pair with the maturity
8. [M-09] DOS pay function (Reentrancy)
In the `pay()` function users repay their debt
| 8 |
14_YieldSourcePrizePool.sol | // SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@pooltogether/yield-source-interface/contracts/IYieldSource.sol";
import "../PrizePool.sol";
contract YieldSourcePrizePool is PrizePool {
using SafeERC20Upgradeable for IERC20Upgradeable;
IYieldSource public yieldSource;
event YieldSourcePrizePoolInitialized(address indexed yieldSource);
/// @notice Initializes the Prize Pool and Yield Service with the required contract connections
/// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool
/// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount
/// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be
/// @param _yieldSource Address of the yield source
function initializeYieldSourcePrizePool (
RegistryInterface _reserveRegistry,
ControlledTokenInterface[] memory _controlledTokens,
uint256 _maxExitFeeMantissa,
uint256 _maxTimelockDuration,
IYieldSource _yieldSource
)
public
initializer
{
require(address(_yieldSource) != address(0), "YieldSourcePrizePool/yield-source-zero");
PrizePool.initialize(
_reserveRegistry,
_controlledTokens,
_maxExitFeeMantissa,
_maxTimelockDuration
);
yieldSource = _yieldSource;
// A hack to determine whether it's an actual yield source
(bool succeeded,) = address(_yieldSource).staticcall(abi.encode(_yieldSource.depositToken.selector));
require(succeeded, "YieldSourcePrizePool/invalid-yield-source");
emit YieldSourcePrizePoolInitialized(address(_yieldSource));
}
/// @notice Determines whether the passed token can be transferred out as an external award.
/// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The
/// prize strategy should not be allowed to move those tokens.
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function _canAwardExternal(address _externalToken) internal override view returns (bool) {
return _externalToken != address(yieldSource);
}
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function _balance() internal override returns (uint256) {
return yieldSource.balanceOfToken(address(this));
}
function _token() internal override view returns (IERC20Upgradeable) {
return IERC20Upgradeable(yieldSource.depositToken());
}
/// @notice Supplies asset tokens to the yield source.
/// @param mintAmount The amount of asset tokens to be supplied
function _supply(uint256 mintAmount) internal override {
_token().safeApprove(address(yieldSource), mintAmount);
yieldSource.supplyTokenTo(mintAmount, address(this));
}
/// @notice Redeems asset tokens from the yield source.
/// @param redeemAmount The amount of yield-bearing tokens to be redeemed
/// @return The actual amount of tokens that were redeemed.
function _redeem(uint256 redeemAmount) internal override returns (uint256) {
return yieldSource.redeemToken(redeemAmount);
}
} | 799 | 82 | 0 | 1. L-01: no check for _stakeToken!=0. (Unchecked value)
The `initializeYieldSourcePrizePool` function of YieldSourcePrizePool.sol has a check to make sure _yieldSource !=0. However, the initialize function of the comparable StakePrizePool.sol doesn't do this check. | 1 |
68_SingleTokenJoinV2.sol | //SPDX-License-Identifier: Unlicense
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {IPangolinRouter} from "@pangolindex/exchange-contracts/contracts/pangolin-periphery/interfaces/IPangolinRouter.sol";
import "../interfaces/IBasketFacet.sol";
contract SingleTokenJoinV2 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Can be any IPangolinRouter or IUniRouter ...
IPangolinRouter public immutable uniSwapLikeRouter;
// WETH or WAVAX ...
IERC20 public immutable INTERMEDIATE_TOKEN;
struct UnderlyingTrade {
UniswapV2SwapStruct[] swaps;
uint256 quantity;
//Quantity to buy
}
struct UniswapV2SwapStruct {
address exchange;
address[] path;
}
struct JoinTokenStructV2 {
address inputToken;
address outputBasket;
uint256 inputAmount;
uint256 outputAmount;
UnderlyingTrade[] trades;
uint256 deadline;
uint16 referral;
}
constructor(address _INTERMEDIATE_TOKEN, address _uniSwapLikeRouter) {
require(_INTERMEDIATE_TOKEN != address(0), "INTERMEDIATE_ZERO");
require(_uniSwapLikeRouter != address(0), "UNI_ROUTER_ZERO");
INTERMEDIATE_TOKEN = IERC20(_INTERMEDIATE_TOKEN);
uniSwapLikeRouter = IPangolinRouter(_uniSwapLikeRouter);
}
function _maxApprove(IERC20 token, address spender) internal {
if (
token.allowance(address(this), spender) <
token.balanceOf(address(this))
) {
token.approve(spender, uint256(-1));
}
}
function joinTokenSingle(JoinTokenStructV2 calldata _joinTokenStruct)
external
{
// ######## INIT TOKEN #########
IERC20 inputToken = IERC20(_joinTokenStruct.inputToken);
inputToken.safeTransferFrom(
msg.sender,
address(this),
_joinTokenStruct.inputAmount
);
_joinTokenSingle(_joinTokenStruct);
// ######## SEND TOKEN #########
uint256 remainingIntermediateBalance = inputToken.balanceOf(
address(this)
);
if (remainingIntermediateBalance > 0) {
inputToken.safeTransfer(msg.sender, remainingIntermediateBalance);
}
}
function _joinTokenSingle(JoinTokenStructV2 calldata _joinTokenStruct)
internal
{
// ######## INIT TOKEN #########
IERC20 outputToken = IERC20(_joinTokenStruct.outputBasket);
for (uint256 i; i < _joinTokenStruct.trades.length; i++) {
UnderlyingTrade calldata trade = _joinTokenStruct.trades[i];
uint256[] memory inputs = new uint256[](trade.swaps.length + 1);
inputs[0] = trade.quantity;
//Get inputs to
for (uint256 j; j < trade.swaps.length; j++) {
UniswapV2SwapStruct calldata swap = trade.swaps[
trade.swaps.length - j - 1
];
uint256[] memory amounts = IPangolinRouter(swap.exchange)
.getAmountsIn(inputs[j], swap.path);
inputs[j + 1] = amounts[0];
}
for (uint256 j; j < trade.swaps.length; j++) {
UniswapV2SwapStruct calldata swap = trade.swaps[j];
uint256 amountIn = inputs[trade.swaps.length - j];
_maxApprove(IERC20(swap.path[0]), address(swap.exchange));
IPangolinRouter(swap.exchange).swapExactTokensForTokens(
amountIn,
0,
swap.path,
address(this),
block.timestamp
);
}
}
address[] memory tokens = IBasketFacet(_joinTokenStruct.outputBasket)
.getTokens();
for (uint256 i; i < tokens.length; i++) {
_maxApprove(IERC20(tokens[i]), _joinTokenStruct.outputBasket);
}
IBasketFacet(_joinTokenStruct.outputBasket).joinPool(
_joinTokenStruct.outputAmount,
_joinTokenStruct.referral
);
// ######## SEND TOKEN #########
uint256 outputAmount = outputToken.balanceOf(address(this));
require(
outputAmount == _joinTokenStruct.outputAmount,
"FAILED_OUTPUT_AMOUNT"
);
outputToken.safeTransfer(msg.sender, outputAmount);
}
} | 1,021 | 137 | 3 | 1. [H-01] Unused ERC20 tokens are not refunded, and can be stolen by attacker. L57-L78
Function `joinTokenSingle`. As a result, the leftover underlying tokens won’t be returned to the user, which constitutes users’ fund loss.
2. [M-01] Function joinTokenSingle in SingleTokenJoin.sol and SingleTokenJoinV2.sol can be made to fail (Gas limit)
There’s a griefing attack vulnerability in the function `_joinTokenSingle` in SingleTokenJoin.sol as well as SingleTokenJoinV2.sol which makes any user transaction fail with “FAILEDOUTPUTAMOUNT”.
3. [M-02] Unchecked return value from low-level call(). (Unchecked return values)
4. [M-06] block.timestamp or deadline. (Timestamp manipulation)
Some functions, like rebalance() in RebalanceManagerV3 use _deadline as a time limit for swapExactTokensForTokens() Other functions, like `_joinTokenSingle()` of SingleTokenJoinV2.sol and _exit() of SingleNativeTokenExitV2() use block.timestamp, although a deadline field is present in the struct. | 4 |
83_MasterChef.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
contract MasterChef is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
event Deposit(address indexed _user, uint indexed _pid, uint _amount);
event Withdraw(address indexed _user, uint indexed _pid, uint _amount);
event EmergencyWithdraw(address indexed user, uint indexed _pid, uint _amount);
struct UserInfo {
uint128 amount;
// How many tokens the user has provided.
uint128 rewardDebt;
// Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of RADSs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accumlatedConcurPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accumlatedConcurPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 depositToken;
// Address of LP token contract.
uint allocPoint;
// How many allocation points assigned to this pool. to distribute per block.
uint lastRewardBlock;
// Last block number that distribution occurs.
uint accConcurPerShare;
// Accumulated per share, times multiplier. See below.
uint16 depositFeeBP;
// Deposit fee in basis points
}
PoolInfo[] public poolInfo;
mapping(uint => mapping(address => UserInfo)) public userInfo;
// Info of each user that stakes LP tokens.
mapping(address => bool) public isDepositor;
mapping(address => uint256) public pid;
// pid mapped to token
uint public concurPerBlock = 100000 gwei;
// concur tokens transferred per block
uint public totalAllocPoint = 0;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint public startBlock;
uint public endBlock;
// The block number when mining starts.
IERC20 public concur;
uint private _concurShareMultiplier = 1e18;
uint private _perMille = 1000;
// 100%
constructor(IERC20 _concur, uint _startBlock, uint _endBlock) Ownable() {
startBlock = _startBlock;
endBlock = _endBlock;
concur = _concur;
poolInfo.push(
PoolInfo({
depositToken: IERC20(address(0)),
allocPoint : 0,
lastRewardBlock : _startBlock,
accConcurPerShare : 0,
depositFeeBP : 0
}));
}
modifier onlyDepositor() {
require(isDepositor[msg.sender], "!depositor");
_;
}
function addDepositor(address _depositor) external onlyOwner {
isDepositor[_depositor] = true;
}
function removeDepositor(address _depositor) external onlyOwner {
isDepositor[_depositor] = false;
}
function add(address _token, uint _allocationPoints, uint16 _depositFee, uint _startBlock) public onlyOwner {
require(_token != address(0), "zero address");
uint lastRewardBlock = block.number > _startBlock ? block.number : _startBlock;
totalAllocPoint = totalAllocPoint.add(_allocationPoints);
require(pid[_token] == 0, "already registered");
// pid starts from 0
poolInfo.push(
PoolInfo({
depositToken: IERC20(_token),
allocPoint: _allocationPoints,
lastRewardBlock: lastRewardBlock,
accConcurPerShare: 0,
depositFeeBP: _depositFee
})
);
pid[_token] = poolInfo.length - 1;
}
function poolLength() external view returns (uint) {
return poolInfo.length;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint _from, uint _to) public pure returns (uint) {
return _to.sub(_from);
}
// View function to see pending [concur] on frontend.
function pendingConcur(uint _pid, address _user) external view returns (uint) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint accConcurPerShare = pool.accConcurPerShare;
uint lpSupply = pool.depositToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint concurReward = multiplier.mul(concurPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accConcurPerShare = accConcurPerShare.add(concurReward.mul(_concurShareMultiplier).div(lpSupply));
}
return user.amount * accConcurPerShare / _concurShareMultiplier - user.rewardDebt;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint length = poolInfo.length;
for (uint _pid = 0; _pid < length; ++_pid) {
updatePool(_pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint lpSupply = pool.depositToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
if(block.number >= endBlock) {
pool.lastRewardBlock = block.number;
return;
}
uint multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint concurReward = multiplier.mul(concurPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accConcurPerShare = pool.accConcurPerShare.add(concurReward.mul(_concurShareMultiplier).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit tokens for [concur] allocation.
function deposit(address _recipient, uint _pid, uint _amount) external nonReentrant onlyDepositor {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
if(user.amount > 0) {
uint pending = user.amount * pool.accConcurPerShare / _concurShareMultiplier - user.rewardDebt;
if (pending > 0) {
safeConcurTransfer(_recipient, pending);
}
}
if (_amount > 0) {
if (pool.depositFeeBP > 0) {
uint depositFee = _amount.mul(pool.depositFeeBP).div(_perMille);
user.amount = SafeCast.toUint128(user.amount + _amount - depositFee);
} else {
user.amount = SafeCast.toUint128(user.amount + _amount);
}
}
user.rewardDebt = SafeCast.toUint128(user.amount * pool.accConcurPerShare / _concurShareMultiplier);
emit Deposit(_recipient, _pid, _amount);
}
// Withdraw tokens
function withdraw(address _recipient, uint _pid, uint _amount) external nonReentrant onlyDepositor {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount > 0, "MasterChef: nothing to withdraw");
require(user.amount >= _amount, "MasterChef: withdraw not allowed");
updatePool(_pid);
uint pending = user.amount * pool.accConcurPerShare / _concurShareMultiplier - user.rewardDebt;
if(pending > 0) {
safeConcurTransfer(_recipient, pending);
}
if (_amount > 0) {
user.amount = SafeCast.toUint128(user.amount - _amount);
}
user.rewardDebt = SafeCast.toUint128(user.amount * pool.accConcurPerShare / _concurShareMultiplier);
emit Withdraw(_recipient, _pid, _amount);
}
// Safe [concur] transfer function, just in case if rounding error causes pool to not have enough
function safeConcurTransfer(address _to, uint _amount) private {
uint concurBalance = concur.balanceOf(address(this));
bool transferSuccess = false;
if (_amount > concurBalance) {
transferSuccess = concur.transfer(_to, concurBalance);
} else {
transferSuccess = concur.transfer(_to, _amount);
}
require(transferSuccess, "safeConcurTransfer: transfer failed");
}
} | 2,120 | 227 | 2 | 1. [H-01] Wrong reward token calculation in MasterChef contract.
`function add(address _token, uint _allocationPoints, uint16 _depositFee, uint _startBlock)`
2. [H-02] Masterchef: Improper handling of `deposit` fee. L170-172
However, the `deposit` fee is not credited to anyone, leading to permanent lockups of deposit fees in the relevant depositor contracts (StakingRewards and ConvexStakingWrapper for now)
3. [H-04] ConvexStakingWrapper, StakingRewards Wrong implementation will send concur rewards to the wrong receiver L159-167
ConvexStakingWrapper, StakingRewards is using masterChef.deposit(), masterChef.withdraw(), and these two functions on masterChef will take _msgSender() as the user address, which is actually the address of ConvexStakingWrapper and StakingRewards.
4. [H-08] MasterChef.sol Users won't be able to receive the concur rewards
Therefore, in `updatePool()` L140 `lpSupply = pool.depositToken.balanceOf(address(this)`) will always be 0. And the updatePool() will be returned at L147.
5. M-02: Unconstrained fee. (Underflow)
Token fee in MasterChef can be set to more than 100%, (for example, by accident) causing all `deposit` calls to fail due to underflow on subtraction when reward is lowered by the fee, thus breaking essential mechanics.
6. M-14: Owner can steal Concur rewards. (Ownership, Centralization Risk)
Function `addDepositor` and `deposit`
7. M-15: Owner can lock tokens in MasterChef. (Ownership, Centralization Risk)
Function `removeDepositor`
8. [M-16] Rewards get diluted because `totalAllocPoint` can only increase.
9. [M-18] Users Will Lose Concur Rewards If The Shelter Mechanism Is Enacted On A Pool
10. [M-20] MasterChef.updatePool() Fails To Update Reward Variables If block.number >= endBlock (Timestamp manipulation)
11. [M-27] MasterChef.sol A `depositor` can deposit an arbitrary amount without no cost
12. [M-28] During stake or deposit, users would not be rewarded the correct Concur token, when MasterChef has under-supply of it | 12 |
71_IndexTemplate.sol | pragma solidity 0.8.7;
/**
* @author InsureDAO
* @title InsureDAO market template contract
* SPDX-License-Identifier: GPL-3.0
*/
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./InsureDAOERC20.sol";
import "./interfaces/IIndexTemplate.sol";
import "./interfaces/IUniversalMarket.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IRegistry.sol";
import "./interfaces/IParameters.sol";
import "./interfaces/IPoolTemplate.sol";
import "./interfaces/ICDSTemplate.sol";
/**
* An index pool can index a certain number of pools with leverage.
*
* Index A
* ├ Pool A
* ├ Pool B
* ├ Pool C
* ...
*
*/
contract IndexTemplate is InsureDAOERC20, IIndexTemplate, IUniversalMarket {
/**
* EVENTS
*/
event Deposit(address indexed depositor, uint256 amount, uint256 mint);
event WithdrawRequested(
address indexed withdrawer,
uint256 amount,
uint256 time
);
event Withdraw(address indexed withdrawer, uint256 amount, uint256 retVal);
event Compensated(address indexed index, uint256 amount);
event Paused(bool paused);
event Resumed();
event Locked();
event MetadataChanged(string metadata);
event LeverageSet(uint256 target);
event AllocationSet(
uint256 indexed _index,
address indexed pool,
uint256 allocPoint
);
/**
* Storage
*/
/// @notice Market setting
bool public initialized;
bool public paused;
bool public locked;
uint256 public pendingEnd;
string public metadata;
/// @notice External contract call addresses
IParameters public parameters;
IVault public vault;
IRegistry public registry;
/// @notice Market variables for margin account
uint256 public totalAllocatedCredit;
//total allocated credit(liquidity)
mapping(address => uint256) public allocPoints;
//allocation point for each pool
uint256 public totalAllocPoint;
//total allocation point
address[] public poolList;
//list of all pools
uint256 public targetLev;
//1x = MAGIC_SCALE_1E6
//The allocated credits are deemed as liquidity in each underlying pool
//Credit amount(liquidity) will be determined by the following math
//credit for a pool = total liquidity of this pool * leverage rate * allocation point for a pool / total allocation point
///@notice user status management
struct Withdrawal {
uint256 timestamp;
uint256 amount;
}
mapping(address => Withdrawal) public withdrawalReq;
struct PoolStatus {
uint256 current;
uint256 available;
uint256 allocation;
address addr;
}
///@notice magic numbers
uint256 public constant MAGIC_SCALE_1E6 = 1e6;
//internal multiplication scale 1e6 to reduce decimal truncation
/**
* @notice Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(
msg.sender == parameters.getOwner(),
"Restricted: caller is not allowed to operate"
);
_;
}
constructor() {
initialized = true;
}
/**
* Initialize interaction
*/
/**
* @notice Initialize market
* This function registers market conditions.
* references[0] = underlying token address
* references[1] = registry
* references[2] = parameter
* @param _metaData arbitrary string to store market information
* @param _conditions array of conditions
* @param _references array of references
*/
function initialize(
string calldata _metaData,
uint256[] calldata _conditions,
address[] calldata _references
) external override {
require(
initialized == false &&
bytes(_metaData).length > 0 &&
_references[0] != address(0) &&
_references[1] != address(0) &&
_references[2] != address(0),
"ERROR: INITIALIZATION_BAD_CONDITIONS"
);
initialized = true;
string memory _name = "InsureDAO-Index";
string memory _symbol = "iIndex";
uint8 _decimals = IERC20Metadata(_references[0]).decimals();
initializeToken(_name, _symbol, _decimals);
parameters = IParameters(_references[2]);
vault = IVault(parameters.getVault(_references[0]));
registry = IRegistry(_references[1]);
metadata = _metaData;
}
/**
* Pool interactions
*/
/**
* @notice A liquidity provider supplies collateral to the pool and receives iTokens
* @param _amount amount of token to deposit
* @return _mintAmount the amount of iToken minted from the transaction
*/
function deposit(uint256 _amount) public returns (uint256 _mintAmount) {
require(locked == false && paused == false, "ERROR: DEPOSIT_DISABLED");
require(_amount > 0, "ERROR: DEPOSIT_ZERO");
uint256 _supply = totalSupply();
uint256 _totalLiquidity = totalLiquidity();
vault.addValue(_amount, msg.sender, address(this));
if (_supply > 0 && _totalLiquidity > 0) {
_mintAmount = (_amount * _supply) / _totalLiquidity;
} else if (_supply > 0 && _totalLiquidity == 0) {
//when
_mintAmount = _amount * _supply;
} else {
_mintAmount = _amount;
}
emit Deposit(msg.sender, _amount, _mintAmount);
//mint iToken
_mint(msg.sender, _mintAmount);
uint256 _liquidityAfter = _totalLiquidity + _amount;
uint256 _leverage = (totalAllocatedCredit * MAGIC_SCALE_1E6) /
_liquidityAfter;
//execut adjustAlloc only when the leverage became below target - lower-slack
if (targetLev - parameters.getLowerSlack(address(this)) > _leverage) {
_adjustAlloc(_liquidityAfter);
}
}
/**
* @notice A liquidity provider requests withdrawal of collateral
* @param _amount amount of iToken to burn
*/
function requestWithdraw(uint256 _amount) external {
uint256 _balance = balanceOf(msg.sender);
require(_balance >= _amount, "ERROR: REQUEST_EXCEED_BALANCE");
require(_amount > 0, "ERROR: REQUEST_ZERO");
withdrawalReq[msg.sender].timestamp = block.timestamp;
withdrawalReq[msg.sender].amount = _amount;
emit WithdrawRequested(msg.sender, _amount, block.timestamp);
}
/**
* @notice A liquidity provider burns iToken and receives collateral from the pool
* @param _amount amount of iToken to burn
* @return _retVal the amount underlying token returned
*/
function withdraw(uint256 _amount) external returns (uint256 _retVal) {
//Calculate underlying value
uint256 _liquidty = totalLiquidity();
uint256 _lockup = parameters.getLockup(msg.sender);
uint256 _requestTime = withdrawalReq[msg.sender].timestamp;
_retVal = (_liquidty * _amount) / totalSupply();
require(locked == false, "ERROR: WITHDRAWAL_PENDING");
require(
_requestTime + _lockup < block.timestamp,
"ERROR: WITHDRAWAL_QUEUE"
);
require(
_requestTime + _lockup + parameters.getWithdrawable(msg.sender) >
block.timestamp,
"ERROR: WITHDRAWAL_NO_ACTIVE_REQUEST"
);
require(
withdrawalReq[msg.sender].amount >= _amount,
"ERROR: WITHDRAWAL_EXCEEDED_REQUEST"
);
require(_amount > 0, "ERROR: WITHDRAWAL_ZERO");
require(
_retVal <= withdrawable(),
"ERROR: WITHDRAW_INSUFFICIENT_LIQUIDITY"
);
//reduce requested amount
withdrawalReq[msg.sender].amount -= _amount;
//Burn iToken
_burn(msg.sender, _amount);
//Check current leverage rate and get updated target total credit allocation
uint256 _liquidityAfter = _liquidty - _retVal;
if (_liquidityAfter > 0) {
uint256 _leverage = (totalAllocatedCredit * MAGIC_SCALE_1E6) /
_liquidityAfter;
//execute adjustAlloc only when the leverage became above target + upper-slack
if (
targetLev + parameters.getUpperSlack(address(this)) < _leverage
) {
_adjustAlloc(_liquidityAfter);
}
} else {
_adjustAlloc(0);
}
//Withdraw liquidity
vault.withdrawValue(_retVal, msg.sender);
emit Withdraw(msg.sender, _amount, _retVal);
}
/**
* @notice Get how much can a user withdraw from this index
* Withdrawable amount = Index liquidity - necessary amount to support credit liquidity
* Necessary amoount Locked * totalAllocPoint / allocpoint of the lowest available liquidity market
* Otherwise, the allocation to a specific pool may take up the overall allocation, and may break the risk sharing.
* @return _retVal withdrawable amount
*/
function withdrawable() public view returns (uint256 _retVal) {
uint256 _totalLiquidity = totalLiquidity();
if(_totalLiquidity > 0){
uint256 _length = poolList.length;
uint256 _lowestAvailableRate = MAGIC_SCALE_1E6;
uint256 _targetAllocPoint;
uint256 _targetLockedCreditScore;
//Check which pool has the lowest available rate and keep stats
for (uint256 i = 0; i < _length; i++) {
address _poolAddress = poolList[i];
uint256 _allocPoint = allocPoints[_poolAddress];
if (_allocPoint > 0) {
uint256 _allocated = IPoolTemplate(_poolAddress)
.allocatedCredit(address(this));
uint256 _availableBalance = IPoolTemplate(_poolAddress)
.availableBalance();
//check if some portion of credit is locked
if (_allocated > _availableBalance) {
uint256 _availableRate = (_availableBalance *
MAGIC_SCALE_1E6) / _allocated;
uint256 _lockedCredit = _allocated - _availableBalance;
if (i == 0 || _availableRate < _lowestAvailableRate) {
_lowestAvailableRate = _availableRate;
_targetLockedCreditScore = _lockedCredit;
_targetAllocPoint = _allocPoint;
}
}
}
}
//Calculate the return value
if (_lowestAvailableRate == MAGIC_SCALE_1E6) {
_retVal = _totalLiquidity;
} else {
uint256 _necessaryAmount = _targetLockedCreditScore * totalAllocPoint / _targetAllocPoint;
_necessaryAmount = _necessaryAmount * MAGIC_SCALE_1E6 / targetLev;
if(_necessaryAmount < _totalLiquidity){
_retVal = _totalLiquidity - _necessaryAmount;
}else{
_retVal = 0;
}
}
}
}
/**
* @notice Adjust allocation of credit based on the target leverage rate
*/
function adjustAlloc() public {
_adjustAlloc(totalLiquidity());
}
/**
* @notice Internal function to adjust allocation
* @param _liquidity available liquidity of the index
* Allocation adjustment of credit is done by the following steps
* 1)Check total allocatable balance of the index
* 2)Calculate ideal allocation for each pool
* 3)Check Current allocated balance for each pool
* 4)Adjust (withdraw/deposit) allocation for each Pool*
*
* Liquidity in pool may be locked and cannot withdraw. In that case, the index try to withdraw all available liquidity first,
* then recalculated available balance and iterate 1)~4) for the remaining.
*
* The index may allocate credit beyond the share settings to maintain the leverage rate not to surpass the leverage setting.
*
* Along with adjustment the index clears accrued premiums in underlying pools to this pool during allocation.
*/
function _adjustAlloc(uint256 _liquidity) internal {
//Check current leverage rate and get target total credit allocation
uint256 _targetCredit = (targetLev * _liquidity) / MAGIC_SCALE_1E6;
uint256 _allocatable = _targetCredit;
uint256 _allocatablePoints = totalAllocPoint;
uint256 _length = poolList.length;
PoolStatus[] memory _poolList = new PoolStatus[](_length);
//Check each pool and if current credit allocation > target && it is impossible to adjust, then withdraw all availablle credit
for (uint256 i = 0; i < _length; i++) {
address _pool = poolList[i];
if (_pool != address(0)) {
uint256 _allocation = allocPoints[_pool];
//Target credit allocation for a pool
uint256 _target = (_targetCredit * _allocation) /
_allocatablePoints;
//get how much has been allocated for a pool
uint256 _current = IPoolTemplate(_pool).allocatedCredit(
address(this)
);
//get how much liquidty is available to withdraw
uint256 _available = IPoolTemplate(_pool).availableBalance();
//if needed to withdraw credit but unable, then withdraw all available.
//Otherwise, skip.
if (
(_current > _target && _current - _target > _available) ||
IPoolTemplate(_pool).paused() == true
) {
IPoolTemplate(_pool).withdrawCredit(_available);
totalAllocatedCredit -= _available;
_poolList[i].addr = address(0);
_allocatable -= _current - _available;
_allocatablePoints -= _allocation;
} else {
_poolList[i].addr = _pool;
_poolList[i].current = _current;
_poolList[i].available = _available;
_poolList[i].allocation = _allocation;
}
}
}
//Check pools that was not falling under the previous criteria, then adjust to meet the target credit allocation.
for (uint256 i = 0; i < _length; i++) {
if (_poolList[i].addr != address(0)) {
//Target credit allocation for a pool
uint256 _target = (_allocatable * _poolList[i].allocation) /
_allocatablePoints;
//get how much has been allocated for a pool
uint256 _current = _poolList[i].current;
//get how much liquidty is available to withdraw
uint256 _available = _poolList[i].available;
//Withdraw or Deposit credit
if (_current > _target && _available != 0) {
//if allocated credit is higher than the target, try to decrease
uint256 _decrease = _current - _target;
IPoolTemplate(_poolList[i].addr).withdrawCredit(_decrease);
totalAllocatedCredit -= _decrease;
}
if (_current < _target) {
//Sometimes we need to allocate more
uint256 _allocate = _target - _current;
IPoolTemplate(_poolList[i].addr).allocateCredit(_allocate);
totalAllocatedCredit += _allocate;
}
if (_current == _target) {
IPoolTemplate(_poolList[i].addr).allocateCredit(0);
}
}
}
}
/**
* Insurance interactions
*/
/**
* @notice Make a payout if an accident occured in a underlying pool
* @param _amount amount of liquidity to compensate for the called pool
* We compensate underlying pools by the following steps
* 1) Compensate underlying pools from the liquidity of this pool
* 2) If this pool is unable to cover a compensation, can get compensated from the CDS pool
*/
function compensate(uint256 _amount)
external
override
returns (uint256 _compensated)
{
require(
allocPoints[msg.sender] > 0,
"ERROR_COMPENSATE_UNAUTHORIZED_CALLER"
);
uint256 _value = vault.underlyingValue(address(this));
if (_value >= _amount) {
//When the deposited value without earned premium is enough to cover
vault.offsetDebt(_amount, msg.sender);
//vault.transferValue(_amount, msg.sender);
_compensated = _amount;
} else {
//Withdraw credit to cashout the earnings
uint256 _shortage;
if (totalLiquidity() < _amount) {
//Insolvency case
_shortage = _amount - _value;
uint256 _cds = ICDSTemplate(registry.getCDS(address(this)))
.compensate(_shortage);
_compensated = _value + _cds;
}
vault.offsetDebt(_compensated, msg.sender);
}
adjustAlloc();
emit Compensated(msg.sender, _compensated);
}
/**
* Reporting interactions
*/
/**
* @notice Resume market
*/
function resume() external override {
uint256 _poolLength = poolList.length;
for (uint256 i = 0; i < _poolLength; i++) {
require(
IPoolTemplate(poolList[i]).paused() == false,
"ERROR: POOL_IS_PAUSED"
);
}
locked = false;
emit Resumed();
}
/**
* @notice lock market withdrawal
*/
function lock() external override {
require(allocPoints[msg.sender] > 0);
locked = true;
emit Locked();
}
/**
* Utilities
*/
/**
* @notice get the current leverage rate 1e6x
* @return _rate leverage rate
*/
function leverage() public view returns (uint256 _rate) {
//check current leverage rate
if (totalLiquidity() > 0) {
return (totalAllocatedCredit * MAGIC_SCALE_1E6) / totalLiquidity();
} else {
return 0;
}
}
/**
* @notice total Liquidity of the pool (how much can the pool sell cover)
* @return _balance total liquidity of the pool
*/
function totalLiquidity() public view returns (uint256 _balance) {
return vault.underlyingValue(address(this)) + _accruedPremiums();
}
/**
* @notice Get the exchange rate of LP token against underlying asset(scaled by MAGIC_SCALE_1E6)
* @return The value against the underlying token balance.
*/
function rate() external view returns (uint256) {
if (totalSupply() > 0) {
return (totalLiquidity() * MAGIC_SCALE_1E6) / totalSupply();
} else {
return 0;
}
}
/**
* @notice Get the underlying balance of the `owner`
* @param _owner the target address to look up value
* @return The balance of underlying token for the specified address
*/
function valueOfUnderlying(address _owner) public view returns (uint256) {
uint256 _balance = balanceOf(_owner);
if (_balance == 0) {
return 0;
} else {
return (_balance * totalLiquidity()) / totalSupply();
}
}
/**
* @notice Get all underlying pools
* @return pool array
*/
function getAllPools() external view returns (address[] memory) {
return poolList;
}
/**
* Admin functions
*/
/**
* @notice Used for changing settlementFeeRecipient
* @param _state true to set paused and vice versa
*/
function setPaused(bool _state) external override onlyOwner {
if (paused != _state) {
paused = _state;
emit Paused(_state);
}
}
/**
* @notice Change metadata string
* @param _metadata new metadata string
*/
function changeMetadata(string calldata _metadata)
external
override
onlyOwner
{
metadata = _metadata;
emit MetadataChanged(_metadata);
}
/**
* @notice Change target leverate rate for this index x 1e6
* @param _target new leverage rate
*/
function setLeverage(uint256 _target) external override onlyOwner {
targetLev = _target;
adjustAlloc();
emit LeverageSet(_target);
}
/**
* @notice Change allocation point for each pool
* @param _index target id of the underlying pool
* @param _pool address of pool
* @param _allocPoint new allocation point
*/
function set(
uint256 _index,
address _pool,
uint256 _allocPoint
) public override onlyOwner {
require(registry.isListed(_pool), "ERROR:UNREGISTERED_POOL");
require(
_index <= parameters.getMaxList(address(this)),
"ERROR: EXCEEEDED_MAX_INDEX"
);
uint256 _length = poolList.length;
//create a new pool or replace existing
if (_length <= _index) {
require(_length == _index, "ERROR: BAD_INDEX");
poolList.push(_pool);
} else {
address _poolAddress = poolList[_index];
if (_poolAddress != address(0) && _poolAddress != _pool) {
uint256 _current = IPoolTemplate(_poolAddress).allocatedCredit(
address(this)
);
IPoolTemplate(_poolAddress).withdrawCredit(_current);
}
poolList[_index] = _pool;
}
if (totalAllocPoint > 0) {
totalAllocPoint =
totalAllocPoint -
allocPoints[_pool] +
_allocPoint;
} else {
totalAllocPoint = _allocPoint;
}
allocPoints[_pool] = _allocPoint;
adjustAlloc();
emit AllocationSet(_index, _pool, _allocPoint);
}
/**
* Internal functions
*/
/**
* @notice Internal function to offset withdraw request and latest balance
* @param from the account who send
* @param to a
* @param amount the amount of token to offset
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from != address(0)) {
uint256 _after = balanceOf(from) - amount;
if (_after < withdrawalReq[from].amount) {
withdrawalReq[from].amount = _after;
}
}
}
/**
* @notice Get the total equivalent value of credit to token
* @return _totalValue accrued but yet claimed premium within underlying pools
*/
function _accruedPremiums() internal view returns (uint256 _totalValue) {
for (uint256 i = 0; i < poolList.length; i++) {
if (allocPoints[poolList[i]] > 0) {
_totalValue =
_totalValue +
IPoolTemplate(poolList[i]).pendingPremium(address(this));
}
}
}
} | 5,171 | 670 | 1 | 1. [H-08] IndexTemplate.sol#compensate() will most certainly fail. (Precision loss)
Precision loss while converting between `the amount of shares` and `the amount of underlying tokens` back and forth is not handled properly.
2. [H-12] IndexTemplate.sol Wrong implementation allows lp of the index pool to resume a locked `PayingOut` pool and escape the responsibility for the compensation
Based on the context, the system intends to lock all the lps during PayingOut period.
However, the current implementation allows anyone, including LPs to call `resume()` and unlock the index pool.
(Access control)
3. [M-04] System Debt Is Not Handled When Insurance Pools Become Insolvent.
| 3 |
112_StakerVault.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../libraries/ScaledMath.sol";
import "../libraries/Errors.sol";
import "../libraries/Errors.sol";
import "../libraries/AddressProviderHelpers.sol";
import "../interfaces/IStakerVault.sol";
import "../interfaces/IAddressProvider.sol";
import "../interfaces/IVault.sol";
import "../interfaces/IController.sol";
import "../interfaces/tokenomics/IRewardsGauge.sol";
import "../interfaces/IController.sol";
import "../interfaces/pool/ILiquidityPool.sol";
import "../interfaces/tokenomics/ILpGauge.sol";
import "../interfaces/IERC20Full.sol";
import "./utils/Preparable.sol";
import "./Controller.sol";
import "./pool/LiquidityPool.sol";
import "./access/Authorization.sol";
import "./utils/Pausable.sol";
/**
* @notice This contract handles staked tokens from Backd pools
* However, not that this is NOT an ERC-20 compliant contract and these
* tokens should never be integrated with any protocol assuming ERC-20 compliant
* tokens
* @dev When paused, allows only withdraw/unstake
*/
contract StakerVault is IStakerVault, Authorization, Pausable, Initializable, Preparable {
using AddressProviderHelpers for IAddressProvider;
using SafeERC20 for IERC20;
using ScaledMath for uint256;
bytes32 internal constant _LP_GAUGE = "lpGauge";
IController public immutable controller;
address public token;
mapping(address => uint256) public balances;
mapping(address => uint256) public actionLockedBalances;
mapping(address => mapping(address => uint256)) internal _allowances;
// All the data fields required for the staking tracking
uint256 private _poolTotalStaked;
mapping(address => bool) public strategies;
uint256 public strategiesTotalStaked;
constructor(IController _controller)
Authorization(_controller.addressProvider().getRoleManager())
{
require(address(_controller) != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
controller = _controller;
}
function initialize(address _token) external override initializer {
token = _token;
}
function initializeLpGauge(address _lpGauge) external override onlyGovernance returns (bool) {
require(currentAddresses[_LP_GAUGE] == address(0), Error.ROLE_EXISTS);
_setConfig(_LP_GAUGE, _lpGauge);
controller.inflationManager().addGaugeForVault(token);
return true;
}
function prepareLpGauge(address _lpGauge) external override onlyGovernance returns (bool) {
_prepare(_LP_GAUGE, _lpGauge);
return true;
}
function executeLpGauge() external override onlyGovernance returns (bool) {
_executeAddress(_LP_GAUGE);
controller.inflationManager().addGaugeForVault(token);
return true;
}
/**
* @notice Registers an address as a strategy to be excluded from token accumulation.
* @dev This should be used is a strategy deposits into a stakerVault and should not get gov. tokens.
* @return `true` if success.
*/
function addStrategy(address strategy) external override returns (bool) {
require(msg.sender == address(controller.inflationManager()), Error.UNAUTHORIZED_ACCESS);
strategies[strategy] = true;
return true;
}
/**
* @notice Transfer staked tokens to an account.
* @dev This is not an ERC20 transfer, as tokens are still owned by this contract, but fees get updated in the LP pool.
* @param account Address to transfer to.
* @param amount Amount to transfer.
* @return `true` if success.
*/
function transfer(address account, uint256 amount) external override notPaused returns (bool) {
require(msg.sender != account, Error.SELF_TRANSFER_NOT_ALLOWED);
require(balances[msg.sender] >= amount, Error.INSUFFICIENT_BALANCE);
ILiquidityPool pool = controller.addressProvider().getPoolForToken(token);
pool.handleLpTokenTransfer(msg.sender, account, amount);
balances[msg.sender] -= amount;
balances[account] += amount;
address lpGauge = currentAddresses[_LP_GAUGE];
if (lpGauge != address(0)) {
ILpGauge(lpGauge).userCheckpoint(msg.sender);
ILpGauge(lpGauge).userCheckpoint(account);
}
emit Transfer(msg.sender, account, amount);
return true;
}
/**
* @notice Transfer staked tokens from src to dst.
* @dev This is not an ERC20 transfer, as tokens are still owned by this contract, but fees get updated in the LP pool.
* @param src Address to transfer from.
* @param dst Address to transfer to.
* @param amount Amount to transfer.
* @return `true` if success.
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external override notPaused returns (bool) {
/* Do not allow self transfers */
require(src != dst, Error.SAME_ADDRESS_NOT_ALLOWED);
address spender = msg.sender;
/* Get the allowance, infinite for the account owner */
uint256 startingAllowance = 0;
if (spender == src) {
startingAllowance = type(uint256).max;
} else {
startingAllowance = _allowances[src][spender];
}
require(startingAllowance >= amount, Error.INSUFFICIENT_BALANCE);
uint256 srcTokens = balances[src];
require(srcTokens >= amount, Error.INSUFFICIENT_BALANCE);
address lpGauge = currentAddresses[_LP_GAUGE];
if (lpGauge != address(0)) {
ILpGauge(lpGauge).userCheckpoint(src);
ILpGauge(lpGauge).userCheckpoint(dst);
}
ILiquidityPool pool = controller.addressProvider().getPoolForToken(token);
pool.handleLpTokenTransfer(src, dst, amount);
uint256 allowanceNew = startingAllowance - amount;
uint256 srcTokensNew = srcTokens - amount;
uint256 dstTokensNew = balances[dst] + amount;
/* Update token balances */
balances[src] = srcTokensNew;
balances[dst] = dstTokensNew;
/* Update allowance if necessary */
if (startingAllowance != type(uint256).max) {
_allowances[src][spender] = allowanceNew;
}
emit Transfer(src, dst, amount);
return true;
}
/**
* @notice Approve staked tokens for spender.
* @param spender Address to approve tokens for.
* @param amount Amount to approve.
* @return `true` if success.
*/
function approve(address spender, uint256 amount) external override notPaused returns (bool) {
address src = msg.sender;
_allowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice If an action is registered and stakes funds, this updates the actionLockedBalances for the user.
* @param account Address that registered the action.
* @param amount Amount staked by the action.
* @return `true` if success.
*/
function increaseActionLockedBalance(address account, uint256 amount)
external
override
returns (bool)
{
require(controller.addressProvider().isAction(msg.sender), Error.UNAUTHORIZED_ACCESS);
address lpGauge = currentAddresses[_LP_GAUGE];
if (lpGauge != address(0)) {
ILpGauge(lpGauge).userCheckpoint(account);
}
actionLockedBalances[account] += amount;
return true;
}
/**
* @notice If an action is executed/reset, this updates the actionLockedBalances for the user.
* @param account Address that registered the action.
* @param amount Amount executed/reset by the action.
* @return `true` if success.
*/
function decreaseActionLockedBalance(address account, uint256 amount)
external
override
returns (bool)
{
require(controller.addressProvider().isAction(msg.sender), Error.UNAUTHORIZED_ACCESS);
address lpGauge = currentAddresses[_LP_GAUGE];
if (lpGauge != address(0)) {
ILpGauge(lpGauge).userCheckpoint(account);
}
if (actionLockedBalances[account] > amount) {
actionLockedBalances[account] -= amount;
} else {
actionLockedBalances[account] = 0;
}
return true;
}
function poolCheckpoint() external override returns (bool) {
if (currentAddresses[_LP_GAUGE] != address(0)) {
return ILpGauge(currentAddresses[_LP_GAUGE]).poolCheckpoint();
}
return false;
}
function getLpGauge() external view override returns (address) {
return currentAddresses[_LP_GAUGE];
}
function isStrategy(address user) external view override returns (bool) {
return strategies[user];
}
/**
* @notice Get the total amount of tokens that are staked by actions
* @return Total amount staked by actions
*/
function getStakedByActions() external view override returns (uint256) {
address[] memory actions = controller.addressProvider().allActions();
uint256 total;
for (uint256 i = 0; i < actions.length; i++) {
total += balances[actions[i]];
}
return total;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function balanceOf(address account) external view override returns (uint256) {
return balances[account];
}
function getPoolTotalStaked() external view override returns (uint256) {
return _poolTotalStaked;
}
/**
* @notice Returns the total balance in the staker vault, including that locked in positions.
* @param account Account to query balance for.
* @return Total balance in staker vault for account.
*/
function stakedAndActionLockedBalanceOf(address account)
external
view
override
returns (uint256)
{
return balances[account] + actionLockedBalances[account];
}
function actionLockedBalanceOf(address account) external view override returns (uint256) {
return actionLockedBalances[account];
}
function decimals() external view returns (uint8) {
return IERC20Full(token).decimals();
}
function getToken() external view override returns (address) {
return token;
}
function unstake(uint256 amount) public override returns (bool) {
return unstakeFor(msg.sender, msg.sender, amount);
}
/**
* @notice Stake an amount of vault tokens.
* @param amount Amount of token to stake.
* @return `true` if success.
*/
function stake(uint256 amount) public override returns (bool) {
return stakeFor(msg.sender, amount);
}
/**
* @notice Stake amount of vault token on behalf of another account.
* @param account Account for which tokens will be staked.
* @param amount Amount of token to stake.
* @return `true` if success.
*/
function stakeFor(address account, uint256 amount) public override notPaused returns (bool) {
require(IERC20(token).balanceOf(msg.sender) >= amount, Error.INSUFFICIENT_BALANCE);
address lpGauge = currentAddresses[_LP_GAUGE];
if (lpGauge != address(0)) {
ILpGauge(lpGauge).userCheckpoint(account);
}
uint256 oldBal = IERC20(token).balanceOf(address(this));
if (msg.sender != account) {
ILiquidityPool pool = controller.addressProvider().getPoolForToken(token);
pool.handleLpTokenTransfer(msg.sender, account, amount);
}
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
uint256 staked = IERC20(token).balanceOf(address(this)) - oldBal;
require(staked == amount, Error.INVALID_AMOUNT);
balances[account] += staked;
if (strategies[account]) {
strategiesTotalStaked += staked;
} else {
_poolTotalStaked += staked;
}
emit Staked(account, amount);
return true;
}
/**
* @notice Unstake tokens on behalf of another account.
* @dev Needs to be approved.
* @param src Account for which tokens will be unstaked.
* @param dst Account receiving the tokens.
* @param amount Amount of token to unstake/receive.
* @return `true` if success.
*/
function unstakeFor(
address src,
address dst,
uint256 amount
) public override returns (bool) {
ILiquidityPool pool = controller.addressProvider().getPoolForToken(token);
uint256 allowance_ = _allowances[src][msg.sender];
require(
src == msg.sender || allowance_ >= amount || address(pool) == msg.sender,
Error.UNAUTHORIZED_ACCESS
);
require(balances[src] >= amount, Error.INSUFFICIENT_BALANCE);
address lpGauge = currentAddresses[_LP_GAUGE];
if (lpGauge != address(0)) {
ILpGauge(lpGauge).userCheckpoint(src);
}
uint256 oldBal = IERC20(token).balanceOf(address(this));
if (src != dst) {
pool.handleLpTokenTransfer(src, dst, amount);
}
IERC20(token).safeTransfer(dst, amount);
uint256 unstaked = oldBal - IERC20(token).balanceOf(address(this));
if (src != msg.sender && allowance_ != type(uint256).max && address(pool) != msg.sender) {
// update allowance
_allowances[src][msg.sender] -= unstaked;
}
balances[src] -= unstaked;
if (strategies[src]) {
strategiesTotalStaked -= unstaked;
} else {
_poolTotalStaked -= unstaked;
}
emit Unstaked(src, amount);
return true;
}
function _isAuthorizedToPause(address account) internal view override returns (bool) {
return _roleManager().hasRole(Roles.GOVERNANCE, account);
}
} | 3,192 | 405 | 1 | 1. [H-01] User can steal all rewards due to checkpoint after transfer.
In StakerVault.sol, the user checkpoints occur AFTER the balances are updated in the `transfer()` function. The user checkpoints update the amount of rewards claimable by the user. Since their rewards will be updated after transfer, a user can send funds between their own accounts and repeatedly claim maximum rewards since the pool's inception.
2. [H-02] function `lockFunds` in TopUpActionLibrary can cause serious fund lose. fee and Capped bypass. It's not calling stakerVault.increaseActionLockedBalance when transfers stakes. L57-L65 (overflow)
Function `increaseActionLockedBalance`, `actionLockedBalances[account] += amount;` | 2 |
64_TwabRewards.sol | // SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@pooltogether/v4-core/contracts/interfaces/ITicket.sol";
import "./interfaces/ITwabRewards.sol";
/**
* @title PoolTogether V4 TwabRewards
* @author PoolTogether Inc Team
* @notice Contract to distribute rewards to depositors in a pool.
* This contract supports the creation of several promotions that can run simultaneously.
* In order to calculate user rewards, we use the TWAB (Time-Weighted Average Balance) from the Ticket contract.
* This way, users simply need to hold their tickets to be eligible to claim rewards.
* Rewards are calculated based on the average amount of tickets they hold during the epoch duration.
* @dev This contract supports only one prize pool ticket.
* @dev This contract does not support the use of fee on transfer tokens.
*/
contract TwabRewards is ITwabRewards {
using SafeERC20 for IERC20;
/* ============ Global Variables ============ */
/// @notice Prize pool ticket for which the promotions are created.
ITicket public immutable ticket;
/// @notice Period during which the promotion owner can't destroy a promotion.
uint32 public constant GRACE_PERIOD = 60 days;
/// @notice Settings of each promotion.
mapping(uint256 => Promotion) internal _promotions;
/**
* @notice Latest recorded promotion id.
* @dev Starts at 0 and is incremented by 1 for each new promotion. So the first promotion will have id 1, the second 2, etc.
*/
uint256 internal _latestPromotionId;
/**
* @notice Keeps track of claimed rewards per user.
* @dev _claimedEpochs[promotionId][user] => claimedEpochs
* @dev We pack epochs claimed by a user into a uint256. So we can't store more than 256 epochs.
*/
mapping(uint256 => mapping(address => uint256)) internal _claimedEpochs;
/* ============ Events ============ */
/**
* @notice Emitted when a promotion is created.
* @param promotionId Id of the newly created promotion
*/
event PromotionCreated(uint256 indexed promotionId);
/**
* @notice Emitted when a promotion is ended.
* @param promotionId Id of the promotion being ended
* @param recipient Address of the recipient that will receive the remaining rewards
* @param amount Amount of tokens transferred to the recipient
* @param epochNumber Epoch number at which the promotion ended
*/
event PromotionEnded(
uint256 indexed promotionId,
address indexed recipient,
uint256 amount,
uint8 epochNumber
);
/**
* @notice Emitted when a promotion is destroyed.
* @param promotionId Id of the promotion being destroyed
* @param recipient Address of the recipient that will receive the unclaimed rewards
* @param amount Amount of tokens transferred to the recipient
*/
event PromotionDestroyed(
uint256 indexed promotionId,
address indexed recipient,
uint256 amount
);
/**
* @notice Emitted when a promotion is extended.
* @param promotionId Id of the promotion being extended
* @param numberOfEpochs Number of epochs the promotion has been extended by
*/
event PromotionExtended(uint256 indexed promotionId, uint256 numberOfEpochs);
/**
* @notice Emitted when rewards have been claimed.
* @param promotionId Id of the promotion for which epoch rewards were claimed
* @param epochIds Ids of the epochs being claimed
* @param user Address of the user for which the rewards were claimed
* @param amount Amount of tokens transferred to the recipient address
*/
event RewardsClaimed(
uint256 indexed promotionId,
uint8[] epochIds,
address indexed user,
uint256 amount
);
/* ============ Constructor ============ */
/**
* @notice Constructor of the contract.
* @param _ticket Prize Pool ticket address for which the promotions will be created
*/
constructor(ITicket _ticket) {
_requireTicket(_ticket);
ticket = _ticket;
}
/* ============ External Functions ============ */
/// @inheritdoc ITwabRewards
function createPromotion(
IERC20 _token,
uint64 _startTimestamp,
uint256 _tokensPerEpoch,
uint48 _epochDuration,
uint8 _numberOfEpochs
) external override returns (uint256) {
require(_tokensPerEpoch > 0, "TwabRewards/tokens-not-zero");
require(_epochDuration > 0, "TwabRewards/duration-not-zero");
_requireNumberOfEpochs(_numberOfEpochs);
uint256 _nextPromotionId = _latestPromotionId + 1;
_latestPromotionId = _nextPromotionId;
uint256 _amount = _tokensPerEpoch * _numberOfEpochs;
_promotions[_nextPromotionId] = Promotion({
creator: msg.sender,
startTimestamp: _startTimestamp,
numberOfEpochs: _numberOfEpochs,
epochDuration: _epochDuration,
createdAt: uint48(block.timestamp),
token: _token,
tokensPerEpoch: _tokensPerEpoch,
rewardsUnclaimed: _amount
});
uint256 _beforeBalance = _token.balanceOf(address(this));
_token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _afterBalance = _token.balanceOf(address(this));
require(_beforeBalance + _amount == _afterBalance, "TwabRewards/promo-amount-diff");
emit PromotionCreated(_nextPromotionId);
return _nextPromotionId;
}
/// @inheritdoc ITwabRewards
function endPromotion(uint256 _promotionId, address _to) external override returns (bool) {
require(_to != address(0), "TwabRewards/payee-not-zero-addr");
Promotion memory _promotion = _getPromotion(_promotionId);
_requirePromotionCreator(_promotion);
_requirePromotionActive(_promotion);
uint8 _epochNumber = uint8(_getCurrentEpochId(_promotion));
_promotions[_promotionId].numberOfEpochs = _epochNumber;
uint256 _remainingRewards = _getRemainingRewards(_promotion);
_promotions[_promotionId].rewardsUnclaimed -= _remainingRewards;
_promotion.token.safeTransfer(_to, _remainingRewards);
emit PromotionEnded(_promotionId, _to, _remainingRewards, _epochNumber);
return true;
}
/// @inheritdoc ITwabRewards
function destroyPromotion(uint256 _promotionId, address _to) external override returns (bool) {
require(_to != address(0), "TwabRewards/payee-not-zero-addr");
Promotion memory _promotion = _getPromotion(_promotionId);
_requirePromotionCreator(_promotion);
uint256 _promotionEndTimestamp = _getPromotionEndTimestamp(_promotion);
uint256 _promotionCreatedAt = _promotion.createdAt;
uint256 _gracePeriodEndTimestamp = (
_promotionEndTimestamp < _promotionCreatedAt
? _promotionCreatedAt
: _promotionEndTimestamp
) + GRACE_PERIOD;
require(block.timestamp >= _gracePeriodEndTimestamp, "TwabRewards/grace-period-active");
uint256 _rewardsUnclaimed = _promotion.rewardsUnclaimed;
delete _promotions[_promotionId];
_promotion.token.safeTransfer(_to, _rewardsUnclaimed);
emit PromotionDestroyed(_promotionId, _to, _rewardsUnclaimed);
return true;
}
/// @inheritdoc ITwabRewards
function extendPromotion(uint256 _promotionId, uint8 _numberOfEpochs)
external
override
returns (bool)
{
_requireNumberOfEpochs(_numberOfEpochs);
Promotion memory _promotion = _getPromotion(_promotionId);
_requirePromotionActive(_promotion);
uint8 _currentNumberOfEpochs = _promotion.numberOfEpochs;
require(
_numberOfEpochs <= (type(uint8).max - _currentNumberOfEpochs),
"TwabRewards/epochs-over-limit"
);
_promotions[_promotionId].numberOfEpochs = _currentNumberOfEpochs + _numberOfEpochs;
uint256 _amount = _numberOfEpochs * _promotion.tokensPerEpoch;
_promotions[_promotionId].rewardsUnclaimed += _amount;
_promotion.token.safeTransferFrom(msg.sender, address(this), _amount);
emit PromotionExtended(_promotionId, _numberOfEpochs);
return true;
}
/// @inheritdoc ITwabRewards
function claimRewards(
address _user,
uint256 _promotionId,
uint8[] calldata _epochIds
) external override returns (uint256) {
Promotion memory _promotion = _getPromotion(_promotionId);
uint256 _rewardsAmount;
uint256 _userClaimedEpochs = _claimedEpochs[_promotionId][_user];
uint256 _epochIdsLength = _epochIds.length;
for (uint256 index = 0; index < _epochIdsLength; index++) {
uint8 _epochId = _epochIds[index];
require(!_isClaimedEpoch(_userClaimedEpochs, _epochId), "TwabRewards/rewards-claimed");
_rewardsAmount += _calculateRewardAmount(_user, _promotion, _epochId);
_userClaimedEpochs = _updateClaimedEpoch(_userClaimedEpochs, _epochId);
}
_claimedEpochs[_promotionId][_user] = _userClaimedEpochs;
_promotions[_promotionId].rewardsUnclaimed -= _rewardsAmount;
_promotion.token.safeTransfer(_user, _rewardsAmount);
emit RewardsClaimed(_promotionId, _epochIds, _user, _rewardsAmount);
return _rewardsAmount;
}
/// @inheritdoc ITwabRewards
function getPromotion(uint256 _promotionId) external view override returns (Promotion memory) {
return _getPromotion(_promotionId);
}
/// @inheritdoc ITwabRewards
function getCurrentEpochId(uint256 _promotionId) external view override returns (uint256) {
return _getCurrentEpochId(_getPromotion(_promotionId));
}
/// @inheritdoc ITwabRewards
function getRemainingRewards(uint256 _promotionId) external view override returns (uint256) {
return _getRemainingRewards(_getPromotion(_promotionId));
}
/// @inheritdoc ITwabRewards
function getRewardsAmount(
address _user,
uint256 _promotionId,
uint8[] calldata _epochIds
) external view override returns (uint256[] memory) {
Promotion memory _promotion = _getPromotion(_promotionId);
uint256 _epochIdsLength = _epochIds.length;
uint256[] memory _rewardsAmount = new uint256[](_epochIdsLength);
for (uint256 index = 0; index < _epochIdsLength; index++) {
if (_isClaimedEpoch(_claimedEpochs[_promotionId][_user], _epochIds[index])) {
_rewardsAmount[index] = 0;
} else {
_rewardsAmount[index] = _calculateRewardAmount(_user, _promotion, _epochIds[index]);
}
}
return _rewardsAmount;
}
/* ============ Internal Functions ============ */
/**
* @notice Determine if address passed is actually a ticket.
* @param _ticket Address to check
*/
function _requireTicket(ITicket _ticket) internal view {
require(address(_ticket) != address(0), "TwabRewards/ticket-not-zero-addr");
(bool succeeded, bytes memory data) = address(_ticket).staticcall(
abi.encodePacked(_ticket.controller.selector)
);
require(
succeeded && data.length > 0 && abi.decode(data, (uint160)) != 0,
"TwabRewards/invalid-ticket"
);
}
/**
* @notice Allow a promotion to be created or extended only by a positive number of epochs.
* @param _numberOfEpochs Number of epochs to check
*/
function _requireNumberOfEpochs(uint8 _numberOfEpochs) internal pure {
require(_numberOfEpochs > 0, "TwabRewards/epochs-not-zero");
}
/**
* @notice Determine if a promotion is active.
* @param _promotion Promotion to check
*/
function _requirePromotionActive(Promotion memory _promotion) internal view {
require(
_getPromotionEndTimestamp(_promotion) > block.timestamp,
"TwabRewards/promotion-inactive"
);
}
/**
* @notice Determine if msg.sender is the promotion creator.
* @param _promotion Promotion to check
*/
function _requirePromotionCreator(Promotion memory _promotion) internal view {
require(msg.sender == _promotion.creator, "TwabRewards/only-promo-creator");
}
/**
* @notice Get settings for a specific promotion.
* @dev Will revert if the promotion does not exist.
* @param _promotionId Promotion id to get settings for
* @return Promotion settings
*/
function _getPromotion(uint256 _promotionId) internal view returns (Promotion memory) {
Promotion memory _promotion = _promotions[_promotionId];
require(_promotion.creator != address(0), "TwabRewards/invalid-promotion");
return _promotion;
}
/**
* @notice Compute promotion end timestamp.
* @param _promotion Promotion to compute end timestamp for
* @return Promotion end timestamp
*/
function _getPromotionEndTimestamp(Promotion memory _promotion)
internal
pure
returns (uint256)
{
unchecked {
return
_promotion.startTimestamp + (_promotion.epochDuration * _promotion.numberOfEpochs);
}
}
/**
* @notice Get the current epoch id of a promotion.
* @dev Epoch ids and their boolean values are tightly packed and stored in a uint256, so epoch id starts at 0.
* @dev We return the current epoch id if the promotion has not ended.
* If the current timestamp is before the promotion start timestamp, we return 0.
* Otherwise, we return the epoch id at the current timestamp. This could be greater than the number of epochs of the promotion.
* @param _promotion Promotion to get current epoch for
* @return Epoch id
*/
function _getCurrentEpochId(Promotion memory _promotion) internal view returns (uint256) {
uint256 _currentEpochId;
if (block.timestamp > _promotion.startTimestamp) {
unchecked {
_currentEpochId =
(block.timestamp - _promotion.startTimestamp) /
_promotion.epochDuration;
}
}
return _currentEpochId;
}
/**
* @notice Get reward amount for a specific user.
* @dev Rewards can only be calculated once the epoch is over.
* @dev Will revert if `_epochId` is over the total number of epochs or if epoch is not over.
* @dev Will return 0 if the user average balance of tickets is 0.
* @param _user User to get reward amount for
* @param _promotion Promotion from which the epoch is
* @param _epochId Epoch id to get reward amount for
* @return Reward amount
*/
function _calculateRewardAmount(
address _user,
Promotion memory _promotion,
uint8 _epochId
) internal view returns (uint256) {
uint64 _epochDuration = _promotion.epochDuration;
uint64 _epochStartTimestamp = _promotion.startTimestamp + (_epochDuration * _epochId);
uint64 _epochEndTimestamp = _epochStartTimestamp + _epochDuration;
require(block.timestamp >= _epochEndTimestamp, "TwabRewards/epoch-not-over");
require(_epochId < _promotion.numberOfEpochs, "TwabRewards/invalid-epoch-id");
uint256 _averageBalance = ticket.getAverageBalanceBetween(
_user,
_epochStartTimestamp,
_epochEndTimestamp
);
if (_averageBalance > 0) {
uint64[] memory _epochStartTimestamps = new uint64[](1);
_epochStartTimestamps[0] = _epochStartTimestamp;
uint64[] memory _epochEndTimestamps = new uint64[](1);
_epochEndTimestamps[0] = _epochEndTimestamp;
uint256 _averageTotalSupply = ticket.getAverageTotalSuppliesBetween(
_epochStartTimestamps,
_epochEndTimestamps
)[0];
return (_promotion.tokensPerEpoch * _averageBalance) / _averageTotalSupply;
}
return 0;
}
/**
* @notice Get the total amount of tokens left to be rewarded.
* @param _promotion Promotion to get the total amount of tokens left to be rewarded for
* @return Amount of tokens left to be rewarded
*/
function _getRemainingRewards(Promotion memory _promotion) internal view returns (uint256) {
if (block.timestamp > _getPromotionEndTimestamp(_promotion)) {
return 0;
}
return
_promotion.tokensPerEpoch *
(_promotion.numberOfEpochs - _getCurrentEpochId(_promotion));
}
function _updateClaimedEpoch(uint256 _userClaimedEpochs, uint8 _epochId)
internal
pure
returns (uint256)
{
return _userClaimedEpochs | (uint256(1) << _epochId);
}
function _isClaimedEpoch(uint256 _userClaimedEpochs, uint8 _epochId)
internal
pure
returns (bool)
{
return (_userClaimedEpochs >> _epochId) & uint256(1) == 1;
}
} | 3,942 | 481 | 3 | 1. [H-01] `createPromotion()` Lack of input validation for _epochDuration can potentially freeze promotion creator's funds
(Input validation)
2. [H-04] `cancelPromotion` is too rigorous
When you cancel a promotion with `cancelPromotion()` then the promotion is complete deleted. This means no-one can claim any rewards anymore, because \_promotions\[\_promotionId] no longer exists.
3. [H-07] Contract does not work with fee-on transfer tokens
This kind of token does not work correctly with the TwabRewards contract as the rewards calculation for an user is based on `_promotion.tokensPerEpoch` (see line 320).
3. [M-01] `cancelPromotion()` Unable to cancel unstarted promotions. (Timestamp manipulation)
For unstarted promotions, cancelPromotion() will revert at `block.timestamp - _promotion.startTimestamp` in _getCurrentEpochId().
4. [M-02] getRewardsAmount doesn't check epochs haven't been claimed (Unbound Loops)
In ITwabRewards.sol, it is claimed that `getRewardsAmount` should account for epochs that have already been claimed, and not include these epochs in the total amount (indeed, there is a line that says @dev Will be 0 if user has already claimed rewards for the epoch.)
5. [M-03] Dust Token Balances Cannot Be Claimed By An admin Account
In `claimRewards`, the `_calculateRewardAmount` calculation may result in truncated results, leading to further accrual of a dust balance. Therefore, it is useful that these funds do not go to waste.
6. [M-04] Unsafe uint64 casting may overflow. (Overflow)
The `_calculateRewardAmount` function casts epoch timestamps from uint256 to uint64 and these may overflow.
7. [M-05] Missing Check When Transferring Tokens Out For A Given Promotion (Unchecked return values)
The `claimRewards` function is called upon by ticket holders who parse a set of _epochIds they wish to claim rewards on. An internal call is made to _calculateRewardAmount to calculate the correct reward amount owed to the user. | 7 |
17_Exposure.sol | // SPDX-License-Identifier: AGPLv3
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../common/StructDefinitions.sol";
import "../common/Constants.sol";
import "../common/Controllable.sol";
import "../common/Whitelist.sol";
import "../interfaces/IERC20Detailed.sol";
import "../interfaces/ILifeGuard.sol";
import "../interfaces/IExposure.sol";
import "../interfaces/IVault.sol";
import "../interfaces/IBuoy.sol";
/// @notice Contract for calculating current protocol exposures on a stablecoin and
/// protocol level. This contract can be upgraded if the systems underlying protocols
/// or tokens have changed. Protocol exposure are calculated at a high level, as any
/// additional exposures from underlying protocol exposures should at most be equal to
/// the high level exposure.
/// For example: harvest finance stablecoin vaults (fTokens)
/// - High level exposure
/// - Harvest finance
/// - Low level exposures (from fToken investments):
/// - Compound
/// - Idle finance
/// Neither of these two low level exposures should matter as long as there arent
/// additional exposure to these protocol elsewhere. So by desing, the protocols
/// are given indexes based on the strategies in the stablecoin vaults, which need
/// to be symetrical for this to work - e.g. all vaults needs to have the same exposure
/// profile, and non of these exposure profiles can overlap. In the case where the
/// additional exposure needs to be taken into account (maker has USDC collateral,
/// Curve adds exposure to all stablecoins in a liquidity pool), they will be calculated
/// and added ontop of the base exposure from vaults and strategies.
///
/// --------------------------------------------------------
/// Current protocol setup:
/// --------------------------------------------------------
/// Stablecoins: DAI, USDC, USDT
/// LP tokens: 3Crv
/// Vaults: DAIVault, USDCVault, USDTVault, 3Crv vault
/// Strategy (exposures):
/// - Compound
/// - Idle finance
/// - Yearn Generic Lender:
/// - Cream
/// - CurveXpool:
/// - Curve3Pool
/// - CurveMetaPool
/// - Yearn
contract Exposure is Constants, Controllable, Whitelist, IExposure {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public protocolCount;
uint256 public makerUSDCExposure;
event LogNewProtocolCount(uint256 count);
event LogNewMakerExposure(uint256 exposure);
/// @notice Add protocol for the exposure calculations
/// @dev Currently set to:
/// 1 - Harvest finance
/// 2 - Cream
/// Curve exposure is calculated separately as it has wider system impact
function setProtocolCount(uint256 _protocolCount) external onlyOwner {
protocolCount = _protocolCount;
emit LogNewProtocolCount(_protocolCount);
}
/// @notice Specify additional USDC exposure to Maker
/// @param _makerUSDCExposure Exposure amount to Maker
function setMakerUSDCExposure(uint256 _makerUSDCExposure) external onlyOwner {
makerUSDCExposure = _makerUSDCExposure;
emit LogNewMakerExposure(_makerUSDCExposure);
}
function getExactRiskExposure(SystemState calldata sysState)
external
view
override
returns (ExposureState memory expState)
{
expState = _calcRiskExposure(sysState, false);
ILifeGuard lifeguard = ILifeGuard(_controller().lifeGuard());
IBuoy buoy = IBuoy(_controller().buoy());
for (uint256 i = 0; i < N_COINS; i++) {
uint256 assets = lifeguard.assets(i);
uint256 assetsUsd = buoy.singleStableToUsd(assets, i);
expState.stablecoinExposure[i] = expState.stablecoinExposure[i].add(
assetsUsd.mul(PERCENTAGE_DECIMAL_FACTOR).div(sysState.totalCurrentAssetsUsd)
);
}
}
/// @notice Calculate stablecoin and protocol level risk exposure
/// @param sysState Struct holding info about systems current state
/// @dev This loops through all the vaults, checks the amount of assets in them
/// and their underlying strategies to understand stablecoin exposure
/// - Any assets invested in Curve or similar AMM will have additional stablecoin exposure.
/// The protocol exposure is calculated by assessing the amount of assets each
/// vault has invested in a strategy.
function calcRiskExposure(SystemState calldata sysState)
external
view
override
returns (ExposureState memory expState)
{
expState = _calcRiskExposure(sysState, true);
// Establish if any stablecoin/protocol is over exposed
(expState.stablecoinExposed, expState.protocolExposed) = isExposed(
sysState.rebalanceThreshold,
expState.stablecoinExposure,
expState.protocolExposure,
expState.curveExposure
);
}
/// @notice Do a rough USD dollar calculation by treating every stablecoin as
/// worth 1 USD and set all Decimals to 18
function getUnifiedAssets(address[N_COINS] calldata vaults)
public
view
override
returns (uint256 unifiedTotalAssets, uint256[N_COINS] memory unifiedAssets)
{
// unify all assets to 18 decimals, treat each stablecoin as being worth 1 USD
for (uint256 i = 0; i < N_COINS; i++) {
uint256 assets = IVault(vaults[i]).totalAssets();
unifiedAssets[i] = assets.mul(DEFAULT_DECIMALS_FACTOR).div(
uint256(10)**IERC20Detailed(IVault(vaults[i]).token()).decimals()
);
unifiedTotalAssets = unifiedTotalAssets.add(unifiedAssets[i]);
}
}
/// @notice Rough delta calculation - assumes each stablecoin is priced at 1 USD,
/// and looks at differences between current allocations and target allocations
/// @param targets Stable coin allocation targest
/// @param vaults Stablecoin vaults
/// @param withdrawUsd USD value of withdrawals
function calcRoughDelta(
uint256[N_COINS] calldata targets,
address[N_COINS] calldata vaults,
uint256 withdrawUsd
) external view override returns (uint256[N_COINS] memory delta) {
(uint256 totalAssets, uint256[N_COINS] memory vaultTotalAssets) = getUnifiedAssets(vaults);
require(totalAssets > withdrawUsd, "totalAssets < withdrawalUsd");
totalAssets = totalAssets.sub(withdrawUsd);
uint256 totalDelta;
for (uint256 i; i < N_COINS; i++) {
uint256 target = totalAssets.mul(targets[i]).div(PERCENTAGE_DECIMAL_FACTOR);
if (vaultTotalAssets[i] > target) {
delta[i] = vaultTotalAssets[i].sub(target);
totalDelta = totalDelta.add(delta[i]);
}
}
uint256 percent = PERCENTAGE_DECIMAL_FACTOR;
for (uint256 i; i < N_COINS - 1; i++) {
if (delta[i] > 0) {
delta[i] = delta[i].mul(PERCENTAGE_DECIMAL_FACTOR).div(totalDelta);
percent = percent.sub(delta[i]);
}
}
delta[N_COINS - 1] = percent;
return delta;
}
/// @notice Sort vaults by the delta of target asset - current asset,
/// only support 3 vaults now
/// @param bigFirst Return array order most exposed -> least exposed
/// @param unifiedTotalAssets Estimated system USD assets
/// @param unifiedAssets Estimated vault USD assets
/// @param targetPercents Vault target percent array
function sortVaultsByDelta(
bool bigFirst,
uint256 unifiedTotalAssets,
uint256[N_COINS] calldata unifiedAssets,
uint256[N_COINS] calldata targetPercents
) external pure override returns (uint256[N_COINS] memory vaultIndexes) {
uint256 maxIndex;
uint256 minIndex;
int256 maxDelta;
int256 minDelta;
for (uint256 i = 0; i < N_COINS; i++) {
// Get difference between vault current assets and vault target
int256 delta = int256(
unifiedAssets[i] - unifiedTotalAssets.mul(targetPercents[i]).div(PERCENTAGE_DECIMAL_FACTOR)
);
// Establish order
if (delta > maxDelta) {
maxDelta = delta;
maxIndex = i;
} else if (delta < minDelta) {
minDelta = delta;
minIndex = i;
}
}
if (bigFirst) {
vaultIndexes[0] = maxIndex;
vaultIndexes[2] = minIndex;
} else {
vaultIndexes[0] = minIndex;
vaultIndexes[2] = maxIndex;
}
vaultIndexes[1] = N_COINS - maxIndex - minIndex;
}
/// @notice Calculate what percentage of system total assets the assets in a strategy make up
/// @param vault Address of target vault that holds the strategy
/// @param index Index of strategy
/// @param vaultAssetsPercent Percentage of system assets
/// @param vaultAssets Total assets in vaults
function calculatePercentOfSystem(
address vault,
uint256 index,
uint256 vaultAssetsPercent,
uint256 vaultAssets
) private view returns (uint256 percentOfSystem) {
if (vaultAssets == 0) return 0;
uint256 strategyAssetsPercent = IVault(vault).getStrategyAssets(index).mul(PERCENTAGE_DECIMAL_FACTOR).div(
vaultAssets
);
percentOfSystem = vaultAssetsPercent.mul(strategyAssetsPercent).div(PERCENTAGE_DECIMAL_FACTOR);
}
/// @notice Calculate the net stablecoin exposure
/// @param directlyExposure Amount of stablecoin in vault+strategies
/// @param curveExposure Percent of assets in Curve
function calculateStableCoinExposure(uint256[N_COINS] memory directlyExposure, uint256 curveExposure)
private
view
returns (uint256[N_COINS] memory stableCoinExposure)
{
uint256 maker = directlyExposure[0].mul(makerUSDCExposure).div(PERCENTAGE_DECIMAL_FACTOR);
for (uint256 i = 0; i < N_COINS; i++) {
uint256 indirectExposure = curveExposure;
if (i == 1) {
indirectExposure = indirectExposure.add(maker);
}
stableCoinExposure[i] = directlyExposure[i].add(indirectExposure);
}
}
/// @notice Determine if an assets or protocol is overexposed
/// @param rebalanceThreshold Threshold for triggering a rebalance due to overexposure
/// @param stableCoinExposure Current stable coin exposures
/// @param protocolExposure Current prtocol exposures
/// @param curveExposure Current Curve exposure
function isExposed(
uint256 rebalanceThreshold,
uint256[N_COINS] memory stableCoinExposure,
uint256[] memory protocolExposure,
uint256 curveExposure
) private pure returns (bool stablecoinExposed, bool protocolExposed) {
for (uint256 i = 0; i < N_COINS; i++) {
if (stableCoinExposure[i] > rebalanceThreshold) {
stablecoinExposed = true;
break;
}
}
for (uint256 i = 0; i < protocolExposure.length; i++) {
if (protocolExposure[i] > rebalanceThreshold) {
protocolExposed = true;
break;
}
}
if (!protocolExposed && curveExposure > rebalanceThreshold) protocolExposed = true;
return (stablecoinExposed, protocolExposed);
}
function _calcRiskExposure(SystemState memory sysState, bool treatLifeguardAsCurve)
private
view
returns (ExposureState memory expState)
{
address[N_COINS] memory vaults = _controller().vaults();
uint256 pCount = protocolCount;
expState.protocolExposure = new uint256[](pCount);
if (sysState.totalCurrentAssetsUsd == 0) {
return expState;
}
// Stablecoin exposure
for (uint256 i = 0; i < N_COINS; i++) {
uint256 vaultAssetsPercent = sysState.vaultCurrentAssetsUsd[i].mul(PERCENTAGE_DECIMAL_FACTOR).div(
sysState.totalCurrentAssetsUsd
);
expState.stablecoinExposure[i] = vaultAssetsPercent;
// Protocol exposure
for (uint256 j = 0; j < pCount; j++) {
uint256 percentOfSystem = calculatePercentOfSystem(
vaults[i],
j,
vaultAssetsPercent,
sysState.vaultCurrentAssets[i]
);
expState.protocolExposure[j] = expState.protocolExposure[j].add(percentOfSystem);
}
}
if (treatLifeguardAsCurve) {
// Curve exposure is calculated by adding the Curve vaults total assets and any
// assets in the lifeguard which are poised to be invested into the Curve vault
expState.curveExposure = sysState.curveCurrentAssetsUsd.add(sysState.lifeguardCurrentAssetsUsd);
} else {
expState.curveExposure = sysState.curveCurrentAssetsUsd;
}
expState.curveExposure = expState.curveExposure.mul(PERCENTAGE_DECIMAL_FACTOR).div(
sysState.totalCurrentAssetsUsd
);
// Calculate stablecoin exposures
expState.stablecoinExposure = calculateStableCoinExposure(expState.stablecoinExposure, expState.curveExposure);
}
} | 3,117 | 319 | 1 | 1. [H-01] implicit underflows. (Overflow)
function `sortVaultsByDelta`. There are a few underflows that are converted via a typecast afterwards to the expected value. If solidity 0.8.x would be used, then the code would revert.
2. [H-04] sortVaultsByDelta doesn't work as expected in `sortVaultsByDelta`
Suppose all the delta's are positive, and delta1 >= delta2 >= delta3 > 0. Then maxIndex = 0. And (delta < minDelta (==0) ) is never true, so minIndex = 0. | 2 |
75_XDEFIDistribution.sol | // SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
import { ERC721, ERC721Enumerable, Strings } from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IEIP2612 } from "./interfaces/IEIP2612.sol";
import { IXDEFIDistribution } from "./interfaces/IXDEFIDistribution.sol";
/// @dev Handles distributing XDEFI to NFTs that have locked up XDEFI for various durations of time.
contract XDEFIDistribution is IXDEFIDistribution, ERC721Enumerable {
uint88 internal MAX_TOTAL_XDEFI_SUPPLY = uint88(240_000_000_000_000_000_000_000_000);
// See https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 internal constant _pointsMultiplier = uint256(2**128);
uint256 internal _pointsPerUnit;
address public immutable XDEFI;
uint256 public distributableXDEFI;
uint256 public totalDepositedXDEFI;
uint256 public totalUnits;
mapping(uint256 => Position) public positionOf;
mapping(uint256 => uint8) public bonusMultiplierOf;
// Scaled by 100 (i.e. 1.1x is 110, 2.55x is 255).
uint256 internal immutable _zeroDurationPointBase;
string public baseURI;
address public owner;
address public pendingOwner;
uint256 internal _locked;
constructor (address XDEFI_, string memory baseURI_, uint256 zeroDurationPointBase_) ERC721("Locked XDEFI", "lXDEFI") {
require((XDEFI = XDEFI_) != address(0), "INVALID_TOKEN");
owner = msg.sender;
baseURI = baseURI_;
_zeroDurationPointBase = zeroDurationPointBase_;
}
modifier onlyOwner() {
require(owner == msg.sender, "NOT_OWNER");
_;
}
modifier noReenter() {
require(_locked == 0, "LOCKED");
_locked = uint256(1);
_;
_locked = uint256(0);
}
/*******************/
/* Admin Functions */
/*******************/
function acceptOwnership() external {
require(pendingOwner == msg.sender, "NOT_PENDING_OWNER");
emit OwnershipAccepted(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
function proposeOwnership(address newOwner_) external onlyOwner {
emit OwnershipProposed(owner, pendingOwner = newOwner_);
}
function setBaseURI(string memory baseURI_) external onlyOwner {
baseURI = baseURI_;
}
function setLockPeriods(uint256[] memory durations_, uint8[] memory multipliers) external onlyOwner {
uint256 count = durations_.length;
for (uint256 i; i < count; ++i) {
uint256 duration = durations_[i];
require(duration <= uint256(18250 days), "INVALID_DURATION");
emit LockPeriodSet(duration, bonusMultiplierOf[duration] = multipliers[i]);
}
}
/**********************/
/* Position Functions */
/**********************/
function lock(uint256 amount_, uint256 duration_, address destination_) external noReenter returns (uint256 tokenId_) {
// Lock the XDEFI in the contract.
SafeERC20.safeTransferFrom(IERC20(XDEFI), msg.sender, address(this), amount_);
// Handle the lock position creation and get the tokenId of the locked position.
return _lock(amount_, duration_, destination_);
}
function lockWithPermit(uint256 amount_, uint256 duration_, address destination_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_) external noReenter returns (uint256 tokenId_) {
// Approve this contract for the amount, using the provided signature.
IEIP2612(XDEFI).permit(msg.sender, address(this), amount_, deadline_, v_, r_, s_);
// Lock the XDEFI in the contract.
SafeERC20.safeTransferFrom(IERC20(XDEFI), msg.sender, address(this), amount_);
// Handle the lock position creation and get the tokenId of the locked position.
return _lock(amount_, duration_, destination_);
}
function relock(uint256 tokenId_, uint256 lockAmount_, uint256 duration_, address destination_) external noReenter returns (uint256 amountUnlocked_, uint256 newTokenId_) {
// Handle the unlock and get the amount of XDEFI eligible to withdraw.
amountUnlocked_ = _unlock(msg.sender, tokenId_);
// Throw convenient error if trying to re-lock more than was unlocked. `amountUnlocked_ - lockAmount_` would have reverted below anyway.
require(lockAmount_ <= amountUnlocked_, "INSUFFICIENT_AMOUNT_UNLOCKED");
// Handle the lock position creation and get the tokenId of the locked position.
newTokenId_ = _lock(lockAmount_, duration_, destination_);
uint256 withdrawAmount = amountUnlocked_ - lockAmount_;
if (withdrawAmount != uint256(0)) {
// Send the excess XDEFI to the destination, if needed.
SafeERC20.safeTransfer(IERC20(XDEFI), destination_, withdrawAmount);
}
// NOTE: This needs to be done after updating `totalDepositedXDEFI` (which happens in `_unlock`) and transferring out.
_updateXDEFIBalance();
}
function unlock(uint256 tokenId_, address destination_) external noReenter returns (uint256 amountUnlocked_) {
// Handle the unlock and get the amount of XDEFI eligible to withdraw.
amountUnlocked_ = _unlock(msg.sender, tokenId_);
// Send the the unlocked XDEFI to the destination.
SafeERC20.safeTransfer(IERC20(XDEFI), destination_, amountUnlocked_);
// NOTE: This needs to be done after updating `totalDepositedXDEFI` (which happens in `_unlock`) and transferring out.
_updateXDEFIBalance();
}
function updateDistribution() external {
uint256 totalUnitsCached = totalUnits;
require(totalUnitsCached > uint256(0), "NO_UNIT_SUPPLY");
uint256 newXDEFI = _toUint256Safe(_updateXDEFIBalance());
if (newXDEFI == uint256(0)) return;
_pointsPerUnit += ((newXDEFI * _pointsMultiplier) / totalUnitsCached);
emit DistributionUpdated(msg.sender, newXDEFI);
}
function withdrawableOf(uint256 tokenId_) public view returns (uint256 withdrawableXDEFI_) {
Position storage position = positionOf[tokenId_];
return _withdrawableGiven(position.units, position.depositedXDEFI, position.pointsCorrection);
}
/****************************/
/* Batch Position Functions */
/****************************/
function relockBatch(uint256[] memory tokenIds_, uint256 lockAmount_, uint256 duration_, address destination_) external noReenter returns (uint256 amountUnlocked_, uint256 newTokenId_) {
// Handle the unlocks and get the amount of XDEFI eligible to withdraw.
amountUnlocked_ = _unlockBatch(msg.sender, tokenIds_);
// Throw convenient error if trying to re-lock more than was unlocked. `amountUnlocked_ - lockAmount_` would have reverted below anyway.
require(lockAmount_ <= amountUnlocked_, "INSUFFICIENT_AMOUNT_UNLOCKED");
// Handle the lock position creation and get the tokenId of the locked position.
newTokenId_ = _lock(lockAmount_, duration_, destination_);
uint256 withdrawAmount = amountUnlocked_ - lockAmount_;
if (withdrawAmount != uint256(0)) {
// Send the excess XDEFI to the destination, if needed.
SafeERC20.safeTransfer(IERC20(XDEFI), destination_, withdrawAmount);
}
// NOTE: This needs to be done after updating `totalDepositedXDEFI` (which happens in `_unlockBatch`) and transferring out.
_updateXDEFIBalance();
}
function unlockBatch(uint256[] memory tokenIds_, address destination_) external noReenter returns (uint256 amountUnlocked_) {
// Handle the unlocks and get the amount of XDEFI eligible to withdraw.
amountUnlocked_ = _unlockBatch(msg.sender, tokenIds_);
// Send the the unlocked XDEFI to the destination.
SafeERC20.safeTransfer(IERC20(XDEFI), destination_, amountUnlocked_);
// NOTE: This needs to be done after updating `totalDepositedXDEFI` (which happens in `_unlockBatch`) and transferring out.
_updateXDEFIBalance();
}
/*****************/
/* NFT Functions */
/*****************/
function getPoints(uint256 amount_, uint256 duration_) external view returns (uint256 points_) {
return _getPoints(amount_, duration_);
}
function merge(uint256[] memory tokenIds_, address destination_) external returns (uint256 tokenId_) {
uint256 count = tokenIds_.length;
require(count > uint256(1), "MIN_2_TO_MERGE");
uint256 points;
// For each NFT, check that it belongs to the caller, burn it, and accumulate the points.
for (uint256 i; i < count; ++i) {
uint256 tokenId = tokenIds_[i];
require(ownerOf(tokenId) == msg.sender, "NOT_OWNER");
require(positionOf[tokenId].expiry == uint32(0), "POSITION_NOT_UNLOCKED");
_burn(tokenId);
points += _getPointsFromTokenId(tokenId);
}
// Mine a new NFT to the destinations, based on the accumulated points.
_safeMint(destination_, tokenId_ = _generateNewTokenId(points));
}
function pointsOf(uint256 tokenId_) external view returns (uint256 points_) {
require(_exists(tokenId_), "NO_TOKEN");
return _getPointsFromTokenId(tokenId_);
}
function tokenURI(uint256 tokenId_) public view override(IXDEFIDistribution, ERC721) returns (string memory tokenURI_) {
require(_exists(tokenId_), "NO_TOKEN");
return string(abi.encodePacked(baseURI, Strings.toString(tokenId_)));
}
/**********************/
/* Internal Functions */
/**********************/
function _generateNewTokenId(uint256 points_) internal view returns (uint256 tokenId_) {
// Points is capped at 128 bits (max supply of XDEFI for 10 years locked), total supply of NFTs is capped at 128 bits.
return (points_ << uint256(128)) + uint128(totalSupply() + 1);
}
function _getPoints(uint256 amount_, uint256 duration_) internal view returns (uint256 points_) {
return amount_ * (duration_ + _zeroDurationPointBase);
}
function _getPointsFromTokenId(uint256 tokenId_) internal pure returns (uint256 points_) {
return tokenId_ >> uint256(128);
}
function _lock(uint256 amount_, uint256 duration_, address destination_) internal returns (uint256 tokenId_) {
// Prevent locking 0 amount in order generate many score-less NFTs, even if it is inefficient, and such NFTs would be ignored.
require(amount_ != uint256(0) && amount_ <= MAX_TOTAL_XDEFI_SUPPLY, "INVALID_AMOUNT");
// Get bonus multiplier and check that it is not zero (which validates the duration).
uint8 bonusMultiplier = bonusMultiplierOf[duration_];
require(bonusMultiplier != uint8(0), "INVALID_DURATION");
// Mint a locked staked position NFT to the destination.
_safeMint(destination_, tokenId_ = _generateNewTokenId(_getPoints(amount_, duration_)));
// Track deposits.
totalDepositedXDEFI += amount_;
// Create Position.
uint96 units = uint96((amount_ * uint256(bonusMultiplier)) / uint256(100));
totalUnits += units;
positionOf[tokenId_] =
Position({
units: units,
depositedXDEFI: uint88(amount_),
expiry: uint32(block.timestamp + duration_),
created: uint32(block.timestamp),
bonusMultiplier: bonusMultiplier,
pointsCorrection: -_toInt256Safe(_pointsPerUnit * units)
});
emit LockPositionCreated(tokenId_, destination_, amount_, duration_);
}
function _toInt256Safe(uint256 x_) internal pure returns (int256 y_) {
y_ = int256(x_);
assert(y_ >= int256(0));
}
function _toUint256Safe(int256 x_) internal pure returns (uint256 y_) {
assert(x_ >= int256(0));
return uint256(x_);
}
function _unlock(address account_, uint256 tokenId_) internal returns (uint256 amountUnlocked_) {
// Check that the account is the position NFT owner.
require(ownerOf(tokenId_) == account_, "NOT_OWNER");
// Fetch position.
Position storage position = positionOf[tokenId_];
uint96 units = position.units;
uint88 depositedXDEFI = position.depositedXDEFI;
uint32 expiry = position.expiry;
// Check that enough time has elapsed in order to unlock.
require(expiry != uint32(0), "NO_LOCKED_POSITION");
require(block.timestamp >= uint256(expiry), "CANNOT_UNLOCK");
// Get the withdrawable amount of XDEFI for the position.
amountUnlocked_ = _withdrawableGiven(units, depositedXDEFI, position.pointsCorrection);
// Track deposits.
totalDepositedXDEFI -= uint256(depositedXDEFI);
// Burn FDT Position.
totalUnits -= units;
delete positionOf[tokenId_];
emit LockPositionWithdrawn(tokenId_, account_, amountUnlocked_);
}
function _unlockBatch(address account_, uint256[] memory tokenIds_) internal returns (uint256 amountUnlocked_) {
uint256 count = tokenIds_.length;
require(count > uint256(1), "USE_UNLOCK");
// Handle the unlock for each position and accumulate the unlocked amount.
for (uint256 i; i < count; ++i) {
amountUnlocked_ += _unlock(account_, tokenIds_[i]);
}
}
function _updateXDEFIBalance() internal returns (int256 newFundsTokenBalance_) {
uint256 previousDistributableXDEFI = distributableXDEFI;
uint256 currentDistributableXDEFI = distributableXDEFI = IERC20(XDEFI).balanceOf(address(this)) - totalDepositedXDEFI;
return _toInt256Safe(currentDistributableXDEFI) - _toInt256Safe(previousDistributableXDEFI);
}
function _withdrawableGiven(uint96 units_, uint88 depositedXDEFI_, int256 pointsCorrection_) internal view returns (uint256 withdrawableXDEFI_) {
return
(
_toUint256Safe(
_toInt256Safe(_pointsPerUnit * uint256(units_)) +
pointsCorrection_
) / _pointsMultiplier
) + uint256(depositedXDEFI_);
}
} | 3,290 | 349 | 1 | 1. [H-01] Malicious early user/attacker can malfunction the contract and even freeze users' funds in edge cases. (Ether Freeze, Centralization risks)
The function `updateDistribution`, `_pointsPerUnit += ((newXDEFI * _pointsMultiplier) / totalUnitsCached);`
2. [H-02] The reentrancy vulnerability in _safeMint can allow an attacker to steal all rewards (Reentrancy)
`_safeMint` function `_checkOnERC721Received`
`lock` function changes the `totalDepositedXDEFI` variable after calling the _safeMint function
Since the `updateDistribution` function does not use the noReenter modifier, the attacker can re-enter the updateDistribution function in the _safeMint function. | 2 |
38_QuickAccManager.sol | // SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.7;
import "../Identity.sol";
import "../interfaces/IERC20.sol";
contract QuickAccManager {
// Note: nonces are scoped by identity rather than by accHash - the reason for this is that there's no reason to scope them by accHash,
// we merely need them for replay protection
mapping (address => uint) nonces;
mapping (bytes32 => uint) scheduled;
bytes4 immutable CANCEL_PREFIX = 0xc47c3100;
// Events
// we only need those for timelocked stuff so we can show scheduled txns to the user; the oens that get executed immediately do not need logs
event LogScheduled(bytes32 indexed txnHash, bytes32 indexed accHash, address indexed signer, uint nonce, uint time, Identity.Transaction[] txns);
event LogCancelled(bytes32 indexed txnHash, bytes32 indexed accHash, address indexed signer, uint time);
event LogExecScheduled(bytes32 indexed txnHash, bytes32 indexed accHash, uint time);
// EIP 2612
bytes32 public DOMAIN_SEPARATOR;
constructor() {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
// @TODO: maybe we should use a more user friendly name here?
keccak256(bytes('QuickAccManager')),
keccak256(bytes('1')),
block.chainid,
address(this)
)
);
}
struct QuickAccount {
uint timelock;
address one;
address two;
// We decided to not allow certain options here such as ability to skip the second sig for send(), but leaving this a struct rather than a tuple
// for clarity and to ensure it's future proof
}
struct DualSig {
bool isBothSigned;
bytes one;
bytes two;
}
// NOTE: a single accHash can control multiple identities, as long as those identities set it's hash in privileges[address(this)]
// this is by design
// isBothSigned is hashed in so that we don't allow signatures from two-sig txns to be reused for single sig txns,
// ...potentially frontrunning a normal two-sig transaction and making it wait
// WARNING: if the signature of this is changed, we have to change IdentityFactory
function send(Identity identity, QuickAccount calldata acc, DualSig calldata sigs, Identity.Transaction[] calldata txns) external {
bytes32 accHash = keccak256(abi.encode(acc));
require(identity.privileges(address(this)) == accHash, 'WRONG_ACC_OR_NO_PRIV');
uint initialNonce = nonces[address(identity)];
// Security: we must also hash in the hash of the QuickAccount, otherwise the sig of one key can be reused across multiple accs
bytes32 hash = keccak256(abi.encode(
address(this),
block.chainid,
accHash,
nonces[address(identity)]++,
txns,
sigs.isBothSigned
));
if (sigs.isBothSigned) {
require(acc.one == SignatureValidator.recoverAddr(hash, sigs.one), 'SIG_ONE');
require(acc.two == SignatureValidator.recoverAddr(hash, sigs.two), 'SIG_TWO');
identity.executeBySender(txns);
} else {
address signer = SignatureValidator.recoverAddr(hash, sigs.one);
require(acc.one == signer || acc.two == signer, 'SIG');
// no need to check whether `scheduled[hash]` is already set here cause of the incrementing nonce
scheduled[hash] = block.timestamp + acc.timelock;
emit LogScheduled(hash, accHash, signer, initialNonce, block.timestamp, txns);
}
}
function cancel(Identity identity, QuickAccount calldata acc, uint nonce, bytes calldata sig, Identity.Transaction[] calldata txns) external {
bytes32 accHash = keccak256(abi.encode(acc));
require(identity.privileges(address(this)) == accHash, 'WRONG_ACC_OR_NO_PRIV');
bytes32 hash = keccak256(abi.encode(CANCEL_PREFIX, address(this), block.chainid, accHash, nonce, txns, false));
address signer = SignatureValidator.recoverAddr(hash, sig);
require(signer == acc.one || signer == acc.two, 'INVALID_SIGNATURE');
// @NOTE: should we allow cancelling even when it's matured? probably not, otherwise there's a minor grief
// opportunity: someone wants to cancel post-maturity, and you front them with execScheduled
bytes32 hashTx = keccak256(abi.encode(address(this), block.chainid, accHash, nonce, txns));
require(scheduled[hashTx] != 0 && block.timestamp < scheduled[hashTx], 'TOO_LATE');
delete scheduled[hashTx];
emit LogCancelled(hashTx, accHash, signer, block.timestamp);
}
function execScheduled(Identity identity, bytes32 accHash, uint nonce, Identity.Transaction[] calldata txns) external {
require(identity.privileges(address(this)) == accHash, 'WRONG_ACC_OR_NO_PRIV');
bytes32 hash = keccak256(abi.encode(address(this), block.chainid, accHash, nonce, txns, false));
require(scheduled[hash] != 0 && block.timestamp >= scheduled[hash], 'NOT_TIME');
delete scheduled[hash];
identity.executeBySender(txns);
emit LogExecScheduled(hash, accHash, block.timestamp);
}
// EIP 1271 implementation
// see https://eips.ethereum.org/EIPS/eip-1271
function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4) {
(address payable id, uint timelock, bytes memory sig1, bytes memory sig2) = abi.decode(signature, (address, uint, bytes, bytes));
bytes32 accHash = keccak256(abi.encode(QuickAccount({
timelock: timelock,
one: SignatureValidator.recoverAddr(hash, sig1),
two: SignatureValidator.recoverAddr(hash, sig2)
})));
if (Identity(id).privileges(address(this)) == accHash) {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
return 0x1626ba7e;
} else {
return 0xffffffff;
}
}
// EIP 712 methods
// all of the following are 2/2 only
bytes32 private TRANSFER_TYPEHASH = keccak256('Transfer(address tokenAddr,address to,uint256 value,uint256 fee,uint256 nonce)');
struct Transfer { address token; address to; uint amount; uint fee; }
// WARNING: if the signature of this is changed, we have to change IdentityFactory
function sendTransfer(Identity identity, QuickAccount calldata acc, bytes calldata sigOne, bytes calldata sigTwo, Transfer calldata t) external {
require(identity.privileges(address(this)) == keccak256(abi.encode(acc)), 'WRONG_ACC_OR_NO_PRIV');
bytes32 hash = keccak256(abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(TRANSFER_TYPEHASH, t.token, t.to, t.amount, t.fee, nonces[address(identity)]++))
));
require(acc.one == SignatureValidator.recoverAddr(hash, sigOne), 'SIG_ONE');
require(acc.two == SignatureValidator.recoverAddr(hash, sigTwo), 'SIG_TWO');
Identity.Transaction[] memory txns = new Identity.Transaction[](2);
txns[0].to = t.token;
txns[0].data = abi.encodeWithSelector(IERC20.transfer.selector, t.to, t.amount);
txns[1].to = t.token;
txns[1].data = abi.encodeWithSelector(IERC20.transfer.selector, msg.sender, t.fee);
identity.executeBySender(txns);
}
// Reference for arrays: https://github.com/sportx-bet/smart-contracts/blob/e36965a0c4748bf73ae15ed3cab5660c9cf722e1/contracts/impl/trading/EIP712FillHasher.sol
// and https://eips.ethereum.org/EIPS/eip-712
// and for signTypedData_v4: https://gist.github.com/danfinlay/750ce1e165a75e1c3387ec38cf452b71
struct Txn { string description; address to; uint value; bytes data; }
bytes32 private TXNS_TYPEHASH = keccak256('Txn(string description,address to,uint256 value,bytes data)');
bytes32 private BUNDLE_TYPEHASH = keccak256('Bundle(uint256 nonce,Txn[] transactions)');
// WARNING: if the signature of this is changed, we have to change IdentityFactory
function sendTxns(Identity identity, QuickAccount calldata acc, bytes calldata sigOne, bytes calldata sigTwo, Txn[] calldata txns) external {
require(identity.privileges(address(this)) == keccak256(abi.encode(acc)), 'WRONG_ACC_OR_NO_PRIV');
// hashing + prepping args
bytes32[] memory txnBytes = new bytes32[](txns.length);
Identity.Transaction[] memory identityTxns = new Identity.Transaction[](txns.length);
for (uint256 i = 0; i < txns.length; i++) {
txnBytes[i] = keccak256(abi.encode(TXNS_TYPEHASH, txns[i].description, txns[i].to, txns[i].value, txns[i].data));
identityTxns[i].to = txns[i].to;
identityTxns[i].value = txns[i].value;
identityTxns[i].data = txns[i].data;
}
bytes32 txnsHash = keccak256(abi.encodePacked(txnBytes));
bytes32 hash = keccak256(abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(BUNDLE_TYPEHASH, nonces[address(identity)]++, txnsHash))
));
require(acc.one == SignatureValidator.recoverAddr(hash, sigOne), 'SIG_ONE');
require(acc.two == SignatureValidator.recoverAddr(hash, sigTwo), 'SIG_TWO');
identity.executeBySender(identityTxns);
}
} | 2,281 | 180 | 0 | 1. [H-02] QuickAccManager.sol#cancel() Wrong hashTx makes it impossible to cancel a scheduled transaction
In QuickAccManager.sol#`cancel()`, the hashTx to identify the transaction to be canceled is wrong. The last parameter is missing.
2. [H-03] Signature replay attacks for different identities (nonce on wrong party)
A single QuickAccount can serve as the "privilege" for multiple identities, see the comment in QuickAccManager.sol
If there exist two different identities that both share the same QuickAccount (`identity1.privileges(address(this)) == identity2.privileges(address(this)) == accHash)` the following attack is possible in
3. [H-04]: `QuickAccManager` Smart Contract signature verification can be exploited (Signature validation)
Several different signature modes can be used and Identity.execute forwards the `signature` parameter to the `SignatureValidator` library. The returned signer is then used for the privileges check: | 3 |
17_Buoy3Pool.sol | // SPDX-License-Identifier: AGPLv3
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {FixedStablecoins} from "contracts/common/FixedContracts.sol";
import {ICurve3Pool} from "contracts/interfaces/ICurve.sol";
import "contracts/common/Controllable.sol";
import "contracts/interfaces/IBuoy.sol";
import "contracts/interfaces/IChainPrice.sol";
import "contracts/interfaces/IChainlinkAggregator.sol";
import "contracts/interfaces/IERC20Detailed.sol";
/// @notice Contract for calculating prices of underlying assets and LP tokens in Curve pool. Also
/// used to sanity check pool against external oracle, to ensure that pools underlying coin ratios
/// are within a specific range (measued in BP) of the external oracles coin price ratios.
/// Sanity check:
/// The Buoy checks previously recorded (cached) curve coin dy, which it compares against current curve dy,
/// blocking any interaction that is outside a certain tolerance (BASIS_POINTS). When updting the cached
/// value, the buoy uses chainlink to ensure that curves prices arent off peg.
contract Buoy3Pool is FixedStablecoins, Controllable, IBuoy, IChainPrice {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 TIME_LIMIT = 3000;
uint256 public BASIS_POINTS = 20;
uint256 constant CHAIN_FACTOR = 100;
ICurve3Pool public immutable override curvePool;
IERC20 public immutable lpToken;
mapping(uint256 => uint256) lastRatio;
// Chianlink price feed
address public immutable daiUsdAgg;
address public immutable usdcUsdAgg;
address public immutable usdtUsdAgg;
mapping(address => mapping(address => uint256)) public tokenRatios;
event LogNewBasisPointLimit(uint256 oldLimit, uint256 newLimit);
constructor(
address _crv3pool,
address poolToken,
address[N_COINS] memory _tokens,
uint256[N_COINS] memory _decimals,
address[N_COINS] memory aggregators
) public FixedStablecoins(_tokens, _decimals) {
curvePool = ICurve3Pool(_crv3pool);
lpToken = IERC20(poolToken);
daiUsdAgg = aggregators[0];
usdcUsdAgg = aggregators[1];
usdtUsdAgg = aggregators[2];
}
/// @notice Set limit for how much Curve pool and external oracle is allowed
/// to deviate before failing transactions
/// @param newLimit New limit in BP
function setBasisPointsLmit(uint256 newLimit) external onlyOwner {
uint256 oldLimit = BASIS_POINTS;
BASIS_POINTS = newLimit;
emit LogNewBasisPointLimit(oldLimit, newLimit);
}
/// @notice Check the health of the Curve pool:
/// Ratios are checked by the following heuristic:
/// Orcale A - Curve
/// Oracle B - External oracle
/// Both oracles establish ratios for a set of stable coins
/// (a, b, c)
/// and product the following set of ratios:
/// (a/a, a/b, a/c), (b/b, b/a, b/c), (c/c, c/a, c/b)
/// It's simply to reduce the number of comparisons to be made
/// in order to have complete coverage of the system ratios:
/// 1) ratios between a stable coin and itself can be discarded
/// 2) inverted ratios, a/b bs b/a, while producing different results
/// should both reflect the same change in any one of the two
/// underlying assets, but in opposite directions
/// This mean that the following set should provide the necessary coverage checks
/// to establish that the coins pricing is healthy:
/// (a/b, a/c)
function safetyCheck() external view override returns (bool) {
for (uint256 i = 1; i < N_COINS; i++) {
uint256 _ratio = curvePool.get_dy(int128(0), int128(i), getDecimal(0));
_ratio = abs(int256(_ratio - lastRatio[i]));
if (_ratio.mul(PERCENTAGE_DECIMAL_FACTOR).div(CURVE_RATIO_DECIMALS_FACTOR) > BASIS_POINTS) {
return false;
}
}
return true;
}
/// @notice Updated cached curve value with a custom tolerance towards chainlink
/// @param tolerance How much difference between curve and chainlink can be tolerated
function updateRatiosWithTolerance(uint256 tolerance) external override returns (bool) {
require(msg.sender == controller || msg.sender == owner(), "updateRatiosWithTolerance: !authorized");
return _updateRatios(tolerance);
}
/// @notice Updated cached curve values
function updateRatios() external override returns (bool) {
require(msg.sender == controller || msg.sender == owner(), "updateRatios: !authorized");
return _updateRatios(BASIS_POINTS);
}
/// @notice Get USD value for a specific input amount of tokens, slippage included
function stableToUsd(uint256[N_COINS] calldata inAmounts, bool deposit) external view override returns (uint256) {
return _stableToUsd(inAmounts, deposit);
}
/// @notice Get estimate USD price of a stablecoin amount
/// @param inAmount Token amount
/// @param i Index of token
function singleStableToUsd(uint256 inAmount, uint256 i) external view override returns (uint256) {
uint256[N_COINS] memory inAmounts;
inAmounts[i] = inAmount;
return _stableToUsd(inAmounts, true);
}
/// @notice Get LP token value of input amount of tokens
function stableToLp(uint256[N_COINS] calldata tokenAmounts, bool deposit) external view override returns (uint256) {
return _stableToLp(tokenAmounts, deposit);
}
/// @notice Get LP token value of input amount of single token
function singleStableFromUsd(uint256 inAmount, int128 i) external view override returns (uint256) {
return _singleStableFromLp(_usdToLp(inAmount), i);
}
/// @notice Get LP token value of input amount of single token
function singleStableFromLp(uint256 inAmount, int128 i) external view override returns (uint256) {
return _singleStableFromLp(inAmount, i);
}
/// @notice Get USD price of LP tokens you receive for a specific input amount of tokens, slippage included
function lpToUsd(uint256 inAmount) external view override returns (uint256) {
return _lpToUsd(inAmount);
}
/// @notice Convert USD amount to LP tokens
function usdToLp(uint256 inAmount) external view override returns (uint256) {
return _usdToLp(inAmount);
}
/// @notice Split LP token amount to balance of pool tokens
/// @param inAmount Amount of LP tokens
/// @param totalBalance Total balance of pool
function poolBalances(uint256 inAmount, uint256 totalBalance)
internal
view
returns (uint256[N_COINS] memory balances)
{
uint256[N_COINS] memory _balances;
for (uint256 i = 0; i < N_COINS; i++) {
_balances[i] = (IERC20(getToken(i)).balanceOf(address(curvePool)).mul(inAmount)).div(totalBalance);
}
balances = _balances;
}
function getVirtualPrice() external view override returns (uint256) {
return curvePool.get_virtual_price();
}
// Internal functions
function _lpToUsd(uint256 inAmount) internal view returns (uint256) {
return inAmount.mul(curvePool.get_virtual_price()).div(DEFAULT_DECIMALS_FACTOR);
}
function _stableToUsd(uint256[N_COINS] memory tokenAmounts, bool deposit) internal view returns (uint256) {
require(tokenAmounts.length == N_COINS, "deposit: !length");
uint256[N_COINS] memory _tokenAmounts;
for (uint256 i = 0; i < N_COINS; i++) {
_tokenAmounts[i] = tokenAmounts[i];
}
uint256 lpAmount = curvePool.calc_token_amount(_tokenAmounts, deposit);
return _lpToUsd(lpAmount);
}
function _stableToLp(uint256[N_COINS] memory tokenAmounts, bool deposit) internal view returns (uint256) {
require(tokenAmounts.length == N_COINS, "deposit: !length");
uint256[N_COINS] memory _tokenAmounts;
for (uint256 i = 0; i < N_COINS; i++) {
_tokenAmounts[i] = tokenAmounts[i];
}
return curvePool.calc_token_amount(_tokenAmounts, deposit);
}
function _singleStableFromLp(uint256 inAmount, int128 i) internal view returns (uint256) {
uint256 result = curvePool.calc_withdraw_one_coin(inAmount, i);
return result;
}
/// @notice Convert USD amount to LP tokens
function _usdToLp(uint256 inAmount) internal view returns (uint256) {
return inAmount.mul(DEFAULT_DECIMALS_FACTOR).div(curvePool.get_virtual_price());
}
/// @notice Calculate price ratios for stablecoins
/// Get USD price data for stablecoin
/// @param i Stablecoin to get USD price for
function getPriceFeed(uint256 i) external view override returns (uint256 _price) {
_price = uint256(IChainlinkAggregator(getAggregator(i)).latestAnswer());
}
/// @notice Fetch chainlink token ratios
/// @param i Token in
function getTokenRatios(uint256 i) private view returns (uint256[3] memory _ratios) {
uint256[3] memory _prices;
_prices[0] = uint256(IChainlinkAggregator(getAggregator(0)).latestAnswer());
_prices[1] = uint256(IChainlinkAggregator(getAggregator(1)).latestAnswer());
_prices[2] = uint256(IChainlinkAggregator(getAggregator(2)).latestAnswer());
for (uint256 j = 0; j < 3; j++) {
if (i == j) {
_ratios[i] = CHAINLINK_PRICE_DECIMAL_FACTOR;
} else {
_ratios[j] = _prices[i].mul(CHAINLINK_PRICE_DECIMAL_FACTOR).div(_prices[j]);
}
}
return _ratios;
}
function getAggregator(uint256 index) private view returns (address) {
if (index == 0) {
return daiUsdAgg;
} else if (index == 1) {
return usdcUsdAgg;
} else {
return usdtUsdAgg;
}
}
/// @notice Get absolute value
function abs(int256 x) private pure returns (uint256) {
return x >= 0 ? uint256(x) : uint256(-x);
}
function _updateRatios(uint256 tolerance) private returns (bool) {
uint256[N_COINS] memory chainRatios = getTokenRatios(0);
uint256[N_COINS] memory newRatios;
for (uint256 i = 1; i < N_COINS; i++) {
uint256 _ratio = curvePool.get_dy(int128(0), int128(i), getDecimal(0));
uint256 check = abs(int256(_ratio) - int256(chainRatios[i].div(CHAIN_FACTOR)));
if (check.mul(PERCENTAGE_DECIMAL_FACTOR).div(CURVE_RATIO_DECIMALS_FACTOR) > tolerance) {
return false;
} else {
newRatios[i] = _ratio;
}
}
for (uint256 i = 1; i < N_COINS; i++) {
lastRatio[i] = newRatios[i];
}
return true;
}
} | 2,761 | 260 | 1 | 1. [H-01] implicit underflows (overflow)
function `safetyCheck()`
2. [H-02] Buoy3Pool.safetyCheck is not precise and has some assumptions (Unclear Function)
3. [M-01] Usage of deprecated ChainLink API in Buoy3Pool (Dependence on Chainlink)
The Chainlink API `latestAnswer` used in the Buoy3Pool oracle wrappers is deprecated
4. [M-05] Use of deprecated Chainlink function latestAnswer. (Dependence on Chainlink)
According to Chainlink's documentation,the `latestAnswer` function is deprecated | 4 |
192_Position.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./utils/MetaContext.sol";
import "./interfaces/IPosition.sol";
contract Position is ERC721Enumerable, MetaContext, IPosition {
function ownerOf(uint _id) public view override(ERC721, IERC721, IPosition) returns (address) {
return ERC721.ownerOf(_id);
}
using Counters for Counters.Counter;
uint constant public DIVISION_CONSTANT = 1e10;
// 100%
mapping(uint => mapping(address => uint)) public vaultFundingPercent;
mapping(address => bool) private _isMinter;
// Trading contract should be minter
mapping(uint256 => Trade) private _trades;
// NFT id to Trade
uint256[] private _openPositions;
mapping(uint256 => uint256) private _openPositionsIndexes;
mapping(uint256 => uint256[]) private _assetOpenPositions;
mapping(uint256 => mapping(uint256 => uint256)) private _assetOpenPositionsIndexes;
mapping(uint256 => uint256[]) private _limitOrders;
// List of limit order nft ids per asset
mapping(uint256 => mapping(uint256 => uint256)) private _limitOrderIndexes;
// Keeps track of asset -> id -> array index
// Funding
mapping(uint256 => mapping(address => int256)) public fundingDeltaPerSec;
mapping(uint256 => mapping(address => mapping(bool => int256))) private accInterestPerOi;
mapping(uint256 => mapping(address => uint256)) private lastUpdate;
mapping(uint256 => int256) private initId;
mapping(uint256 => mapping(address => uint256)) private longOi;
mapping(uint256 => mapping(address => uint256)) private shortOi;
function isMinter(address _address) public view returns (bool) { return _isMinter[_address]; }
function trades(uint _id) public view returns (Trade memory) {
Trade memory _trade = _trades[_id];
_trade.trader = ownerOf(_id);
if (_trade.orderType > 0) return _trade;
int256 _pendingFunding;
if (_trade.direction && longOi[_trade.asset][_trade.tigAsset] > 0) {
_pendingFunding = (int256(block.timestamp-lastUpdate[_trade.asset][_trade.tigAsset])*fundingDeltaPerSec[_trade.asset][_trade.tigAsset])*1e18/int256(longOi[_trade.asset][_trade.tigAsset]);
if (longOi[_trade.asset][_trade.tigAsset] > shortOi[_trade.asset][_trade.tigAsset]) {
_pendingFunding = -_pendingFunding;
} else {
_pendingFunding = _pendingFunding*int256(1e10-vaultFundingPercent[_trade.asset][_trade.tigAsset])/1e10;
}
} else if (shortOi[_trade.asset][_trade.tigAsset] > 0) {
_pendingFunding = (int256(block.timestamp-lastUpdate[_trade.asset][_trade.tigAsset])*fundingDeltaPerSec[_trade.asset][_trade.tigAsset])*1e18/int256(shortOi[_trade.asset][_trade.tigAsset]);
if (shortOi[_trade.asset][_trade.tigAsset] > longOi[_trade.asset][_trade.tigAsset]) {
_pendingFunding = -_pendingFunding;
} else {
_pendingFunding = _pendingFunding*int256(1e10-vaultFundingPercent[_trade.asset][_trade.tigAsset])/1e10;
}
}
_trade.accInterest += (int256(_trade.margin*_trade.leverage/1e18)*(accInterestPerOi[_trade.asset][_trade.tigAsset][_trade.direction]+_pendingFunding)/1e18)-initId[_id];
return _trade;
}
function openPositions() public view returns (uint256[] memory) { return _openPositions; }
function openPositionsIndexes(uint _id) public view returns (uint256) { return _openPositionsIndexes[_id]; }
function assetOpenPositions(uint _asset) public view returns (uint256[] memory) { return _assetOpenPositions[_asset]; }
function assetOpenPositionsIndexes(uint _asset, uint _id) public view returns (uint256) { return _assetOpenPositionsIndexes[_asset][_id]; }
function limitOrders(uint _asset) public view returns (uint256[] memory) { return _limitOrders[_asset]; }
function limitOrderIndexes(uint _asset, uint _id) public view returns (uint256) { return _limitOrderIndexes[_asset][_id]; }
Counters.Counter private _tokenIds;
string public baseURI;
constructor(string memory _setBaseURI, string memory _name, string memory _symbol) ERC721(_name, _symbol) {
baseURI = _setBaseURI;
_tokenIds.increment();
}
function _baseURI() internal override view returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
/**
* @notice Update funding rate after open interest change
* @dev only callable by minter
* @param _asset pair id
* @param _tigAsset tigAsset token address
* @param _longOi long open interest
* @param _shortOi short open interest
* @param _baseFundingRate base funding rate of a pair
* @param _vaultFundingPercent percent of earned funding going to the stablevault
*/
function updateFunding(uint256 _asset, address _tigAsset, uint256 _longOi, uint256 _shortOi, uint256 _baseFundingRate, uint _vaultFundingPercent) external onlyMinter {
if(longOi[_asset][_tigAsset] < shortOi[_asset][_tigAsset]) {
if (longOi[_asset][_tigAsset] > 0) {
accInterestPerOi[_asset][_tigAsset][true] += ((int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(longOi[_asset][_tigAsset]))*int256(1e10-vaultFundingPercent[_asset][_tigAsset])/1e10;
}
accInterestPerOi[_asset][_tigAsset][false] -= (int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(shortOi[_asset][_tigAsset]);
} else if(longOi[_asset][_tigAsset] > shortOi[_asset][_tigAsset]) {
accInterestPerOi[_asset][_tigAsset][true] -= (int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(longOi[_asset][_tigAsset]);
if (shortOi[_asset][_tigAsset] > 0) {
accInterestPerOi[_asset][_tigAsset][false] += ((int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(shortOi[_asset][_tigAsset]))*int256(1e10-vaultFundingPercent[_asset][_tigAsset])/1e10;
}
}
lastUpdate[_asset][_tigAsset] = block.timestamp;
int256 _oiDelta;
if (_longOi > _shortOi) {
_oiDelta = int256(_longOi)-int256(_shortOi);
} else {
_oiDelta = int256(_shortOi)-int256(_longOi);
}
fundingDeltaPerSec[_asset][_tigAsset] = (_oiDelta*int256(_baseFundingRate)/int256(DIVISION_CONSTANT))/31536000;
longOi[_asset][_tigAsset] = _longOi;
shortOi[_asset][_tigAsset] = _shortOi;
vaultFundingPercent[_asset][_tigAsset] = _vaultFundingPercent;
}
/**
* @notice mint a new position nft
* @dev only callable by minter
* @param _mintTrade New trade params in struct
*/
function mint(
MintTrade memory _mintTrade
) external onlyMinter {
uint newTokenID = _tokenIds.current();
Trade storage newTrade = _trades[newTokenID];
newTrade.margin = _mintTrade.margin;
newTrade.leverage = _mintTrade.leverage;
newTrade.asset = _mintTrade.asset;
newTrade.direction = _mintTrade.direction;
newTrade.price = _mintTrade.price;
newTrade.tpPrice = _mintTrade.tp;
newTrade.slPrice = _mintTrade.sl;
newTrade.orderType = _mintTrade.orderType;
newTrade.id = newTokenID;
newTrade.tigAsset = _mintTrade.tigAsset;
_safeMint(_mintTrade.account, newTokenID);
if (_mintTrade.orderType > 0) {
_limitOrders[_mintTrade.asset].push(newTokenID);
_limitOrderIndexes[_mintTrade.asset][newTokenID] = _limitOrders[_mintTrade.asset].length-1;
} else {
initId[newTokenID] = accInterestPerOi[_mintTrade.asset][_mintTrade.tigAsset][_mintTrade.direction]*int256(_mintTrade.margin*_mintTrade.leverage/1e18)/1e18;
_openPositions.push(newTokenID);
_openPositionsIndexes[newTokenID] = _openPositions.length-1;
_assetOpenPositions[_mintTrade.asset].push(newTokenID);
_assetOpenPositionsIndexes[_mintTrade.asset][newTokenID] = _assetOpenPositions[_mintTrade.asset].length-1;
}
_tokenIds.increment();
}
/**
* @param _id id of the position NFT
* @param _price price used for execution
* @param _newMargin margin after fees
*/
function executeLimitOrder(uint256 _id, uint256 _price, uint256 _newMargin) external onlyMinter {
Trade storage _trade = _trades[_id];
if (_trade.orderType == 0) {
return;
}
_trade.orderType = 0;
_trade.price = _price;
_trade.margin = _newMargin;
uint _asset = _trade.asset;
_limitOrderIndexes[_asset][_limitOrders[_asset][_limitOrders[_asset].length-1]] = _limitOrderIndexes[_asset][_id];
_limitOrders[_asset][_limitOrderIndexes[_asset][_id]] = _limitOrders[_asset][_limitOrders[_asset].length-1];
delete _limitOrderIndexes[_asset][_id];
_limitOrders[_asset].pop();
_openPositions.push(_id);
_openPositionsIndexes[_id] = _openPositions.length-1;
_assetOpenPositions[_asset].push(_id);
_assetOpenPositionsIndexes[_asset][_id] = _assetOpenPositions[_asset].length-1;
initId[_id] = accInterestPerOi[_trade.asset][_trade.tigAsset][_trade.direction]*int256(_trade.margin*_trade.leverage/1e18)/1e18;
}
/**
* @notice modifies margin and leverage
* @dev only callable by minter
* @param _id position id
* @param _newMargin new margin amount
* @param _newLeverage new leverage amount
*/
function modifyMargin(uint256 _id, uint256 _newMargin, uint256 _newLeverage) external onlyMinter {
_trades[_id].margin = _newMargin;
_trades[_id].leverage = _newLeverage;
}
/**
* @notice modifies margin and entry price
* @dev only callable by minter
* @param _id position id
* @param _newMargin new margin amount
* @param _newPrice new entry price
*/
function addToPosition(uint256 _id, uint256 _newMargin, uint256 _newPrice) external onlyMinter {
_trades[_id].margin = _newMargin;
_trades[_id].price = _newPrice;
initId[_id] = accInterestPerOi[_trades[_id].asset][_trades[_id].tigAsset][_trades[_id].direction]*int256(_newMargin*_trades[_id].leverage/1e18)/1e18;
}
/**
* @notice Called before updateFunding for reducing position or adding to position, to store accumulated funding
* @dev only callable by minter
* @param _id position id
*/
function setAccInterest(uint256 _id) external onlyMinter {
_trades[_id].accInterest = trades(_id).accInterest;
}
/**
* @notice Reduces position size by %
* @dev only callable by minter
* @param _id position id
* @param _percent percent of a position being closed
*/
function reducePosition(uint256 _id, uint256 _percent) external onlyMinter {
_trades[_id].accInterest -= _trades[_id].accInterest*int256(_percent)/int256(DIVISION_CONSTANT);
_trades[_id].margin -= _trades[_id].margin*_percent/DIVISION_CONSTANT;
initId[_id] = accInterestPerOi[_trades[_id].asset][_trades[_id].tigAsset][_trades[_id].direction]*int256(_trades[_id].margin*_trades[_id].leverage/1e18)/1e18;
}
/**
* @notice change a position tp price
* @dev only callable by minter
* @param _id position id
* @param _tpPrice tp price
*/
function modifyTp(uint _id, uint _tpPrice) external onlyMinter {
_trades[_id].tpPrice = _tpPrice;
}
/**
* @notice change a position sl price
* @dev only callable by minter
* @param _id position id
* @param _slPrice sl price
*/
function modifySl(uint _id, uint _slPrice) external onlyMinter {
_trades[_id].slPrice = _slPrice;
}
/**
* @dev Burns an NFT and it's data
* @param _id ID of the trade
*/
function burn(uint _id) external onlyMinter {
_burn(_id);
uint _asset = _trades[_id].asset;
if (_trades[_id].orderType > 0) {
_limitOrderIndexes[_asset][_limitOrders[_asset][_limitOrders[_asset].length-1]] = _limitOrderIndexes[_asset][_id];
_limitOrders[_asset][_limitOrderIndexes[_asset][_id]] = _limitOrders[_asset][_limitOrders[_asset].length-1];
delete _limitOrderIndexes[_asset][_id];
_limitOrders[_asset].pop();
} else {
_assetOpenPositionsIndexes[_asset][_assetOpenPositions[_asset][_assetOpenPositions[_asset].length-1]] = _assetOpenPositionsIndexes[_asset][_id];
_assetOpenPositions[_asset][_assetOpenPositionsIndexes[_asset][_id]] = _assetOpenPositions[_asset][_assetOpenPositions[_asset].length-1];
delete _assetOpenPositionsIndexes[_asset][_id];
_assetOpenPositions[_asset].pop();
_openPositionsIndexes[_openPositions[_openPositions.length-1]] = _openPositionsIndexes[_id];
_openPositions[_openPositionsIndexes[_id]] = _openPositions[_openPositions.length-1];
delete _openPositionsIndexes[_id];
_openPositions.pop();
}
delete _trades[_id];
}
function assetOpenPositionsLength(uint _asset) external view returns (uint256) {
return _assetOpenPositions[_asset].length;
}
function limitOrdersLength(uint _asset) external view returns (uint256) {
return _limitOrders[_asset].length;
}
function getCount() external view returns (uint) {
return _tokenIds.current();
}
function userTrades(address _user) external view returns (uint[] memory) {
uint[] memory _ids = new uint[](balanceOf(_user));
for (uint i=0; i<_ids.length; i++) {
_ids[i] = tokenOfOwnerByIndex(_user, i);
}
return _ids;
}
function openPositionsSelection(uint _from, uint _to) external view returns (uint[] memory) {
uint[] memory _ids = new uint[](_to-_from);
for (uint i=0; i<_ids.length; i++) {
_ids[i] = _openPositions[i+_from];
}
return _ids;
}
function setMinter(address _minter, bool _bool) external onlyOwner {
_isMinter[_minter] = _bool;
}
modifier onlyMinter() {
require(_isMinter[_msgSender()], "!Minter");
_;
}
// META-TX
function _msgSender() internal view override(Context, MetaContext) returns (address sender) {
return MetaContext._msgSender();
}
function _msgData() internal view override(Context, MetaContext) returns (bytes calldata) {
return MetaContext._msgData();
}
} | 3,889 | 331 | 1 | 1. [H-07] reentrancy attack during `mint()`function in Position contract which can lead to removing of the other user's limit orders or stealing contract funds because initId is set low value
(Reentrancy) | 1 |
5_USDV.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
// Interfaces
import "./interfaces/iERC20.sol";
import "./interfaces/iVADER.sol";
import "./interfaces/iROUTER.sol";
contract USDV is iERC20 {
// ERC-20 Parameters
string public override name; string public override symbol;
uint public override decimals; uint public override totalSupply;
// ERC-20 Mappings
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
// Parameters
bool private inited;
uint public nextEraTime;
uint public blockDelay;
address public VADER;
address public VAULT;
address public ROUTER;
mapping(address => uint) public lastBlock;
// Only DAO can execute
modifier onlyDAO() {
require(msg.sender == DAO(), "Not DAO");
_;
}
// Stop flash attacks
modifier flashProof() {
require(isMature(), "No flash");
_;
}
function isMature() public view returns(bool isMatured){
if(lastBlock[tx.origin] + blockDelay <= block.number){
return true;
}
}
//=====================================CREATION=========================================//
// Constructor
constructor() {
name = 'VADER STABLE DOLLAR';
symbol = 'USDV';
decimals = 18;
totalSupply = 0;
}
function init(address _vader, address _vault, address _router) external {
require(inited == false);
inited = true;
VADER = _vader;
VAULT = _vault;
ROUTER = _router;
nextEraTime = block.timestamp + iVADER(VADER).secondsPerEra();
}
//========================================iERC20=========================================//
function balanceOf(address account) public view override returns (uint) {
return _balances[account];
}
function allowance(address owner, address spender) public view virtual override returns (uint) {
return _allowances[owner][spender];
}
// iERC20 Transfer function
function transfer(address recipient, uint amount) external virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
// iERC20 Approve, change allowance functions
function approve(address spender, uint amount) external virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function _approve(address owner, address spender, uint amount) internal virtual {
require(owner != address(0), "sender");
require(spender != address(0), "spender");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// iERC20 TransferFrom function
function transferFrom(address sender, address recipient, uint amount) external virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender] - amount);
return true;
}
// TransferTo function
// Risks: User can be phished, or tx.origin may be deprecated, optionality should exist in the system.
function transferTo(address recipient, uint amount) external virtual override returns (bool) {
_transfer(tx.origin, recipient, amount);
return true;
}
// Internal transfer function
function _transfer(address sender, address recipient, uint amount) internal virtual {
if(amount > 0){
require(sender != address(0), "sender");
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_checkIncentives();
}
}
// Internal mint (upgrading and daily emissions)
function _mint(address account, uint amount) internal virtual {
if(amount > 0){
require(account != address(0), "recipient");
totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
}
// Burn supply
function burn(uint amount) external virtual override {
_burn(msg.sender, amount);
}
function burnFrom(address account, uint amount) external virtual override {
uint decreasedAllowance = allowance(account, msg.sender)- amount;
_approve(account, msg.sender, decreasedAllowance);
_burn(account, amount);
}
function _burn(address account, uint amount) internal virtual {
if(amount > 0){
require(account != address(0), "address err");
_balances[account] -= amount;
totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
}
//=========================================DAO=========================================//
// Can set params
function setParams(uint newDelay) external onlyDAO {
blockDelay = newDelay;
}
//======================================INCENTIVES========================================//
// Internal - Update incentives function
function _checkIncentives() private {
if (block.timestamp >= nextEraTime && emitting()) {
nextEraTime = block.timestamp + iVADER(VADER).secondsPerEra();
uint _balance = iERC20(VADER).balanceOf(address(this));
if(_balance > 4){
uint _USDVShare = _balance/2;
_convert(address(this), _USDVShare);
if(balanceOf(address(this)) > 2){
_transfer(address(this), ROUTER, balanceOf(address(this)) / 2);
_transfer(address(this), VAULT, balanceOf(address(this)));
}
iERC20(VADER).transfer(ROUTER, iERC20(VADER).balanceOf(address(this))/2);
iERC20(VADER).transfer(VAULT, iERC20(VADER).balanceOf(address(this)));
}
}
}
//======================================ASSET MINTING========================================//
// Convert to USDV
function convert(uint amount) external returns(uint) {
return convertForMember(msg.sender, amount);
}
// Convert for members
function convertForMember(address member, uint amount) public returns(uint) {
getFunds(VADER, amount);
return _convert(member, amount);
}
// Internal convert
function _convert(address _member, uint amount) internal flashProof returns(uint _convertAmount){
if(minting()){
lastBlock[tx.origin] = block.number;
iERC20(VADER).burn(amount);
_convertAmount = iROUTER(ROUTER).getUSDVAmount(amount);
_mint(_member, _convertAmount);
}
}
// Redeem to VADER
function redeem(uint amount) external returns(uint) {
return redeemForMember(msg.sender, amount);
}
// Contracts to redeem for members
function redeemForMember(address member, uint amount) public returns(uint redeemAmount) {
_transfer(msg.sender, VADER, amount);
redeemAmount = iVADER(VADER).redeemToMember(member);
lastBlock[tx.origin] = block.number;
}
//============================== ASSETS ================================//
function getFunds(address token, uint amount) internal {
if(token == address(this)){
_transfer(msg.sender, address(this), amount);
} else {
if(tx.origin==msg.sender){
require(iERC20(token).transferTo(address(this), amount));
}else{
require(iERC20(token).transferFrom(msg.sender, address(this), amount));
}
}
}
//============================== HELPERS ================================//
function DAO() public view returns(address){
return iVADER(VADER).DAO();
}
function emitting() public view returns(bool){
return iVADER(VADER).emitting();
}
function minting() public view returns(bool){
return iVADER(VADER).minting();
}
} | 1,713 | 219 | 2 | 1. [H-02] Flash attack mitigation does not work as intended in USDV.sol (Flash loan attack prevention)
One of the stated protocol (review) goals is to detect susceptibility to “Any attack vectors using flash loans on Anchor price, synths or lending.” As such, USDV contract aims to protect against flash attacks using `flashProof()` modifier which uses the following check in `isMature()` to determine if currently executing contract context is at least `blockDelay` duration ahead of the previous context: `lastBlock[tx.origin] + blockDelay <= block.number`
2. [M-13] Init function can be called by everyone (Access control, Unprotect init() function)
Most of the solidity contracts have an init function that everyone can call. This could lead to a race condition when the contract is deployed. At that moment a hacker could call the `init` function and make the deployed contracts useless. Then it would have to be redeployed, costing a lot of gas.
3. [M-17] Vader.redeemToMember() vulnerable to front running (Front-running) | 3 |
58_UniV3Vault.sol | // SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/external/univ3/INonfungiblePositionManager.sol";
import "./interfaces/external/univ3/IUniswapV3Pool.sol";
import "./interfaces/external/univ3/IUniswapV3Factory.sol";
import "./interfaces/IUniV3VaultGovernance.sol";
import "./libraries/external/TickMath.sol";
import "./libraries/external/LiquidityAmounts.sol";
import "./Vault.sol";
import "./libraries/ExceptionsLibrary.sol";
/// @notice Vault that interfaces UniswapV3 protocol in the integration layer.
contract UniV3Vault is IERC721Receiver, Vault {
struct Options {
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct Pair {
uint256 a0;
uint256 a1;
}
IUniswapV3Pool public immutable pool;
uint256 public uniV3Nft;
/// @notice Creates a new contract.
/// @param vaultGovernance_ Reference to VaultGovernance for this vault
/// @param vaultTokens_ ERC20 tokens under Vault management
/// @param fee Fee of the underlying UniV3 pool
constructor(
IVaultGovernance vaultGovernance_,
address[] memory vaultTokens_,
uint24 fee
) Vault(vaultGovernance_, vaultTokens_) {
require(_vaultTokens.length == 2, ExceptionsLibrary.TOKEN_LENGTH);
pool = IUniswapV3Pool(
IUniswapV3Factory(_positionManager().factory()).getPool(_vaultTokens[0], _vaultTokens[1], fee)
);
}
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory) external returns (bytes4) {
require(msg.sender == address(_positionManager()), "SNFT");
require(_isStrategy(operator), "STR");
(
, ,
address token0,
address token1,
, , , , , , ,
) = _positionManager().positions(tokenId);
// new position should have vault tokens
require(
token0 == _vaultTokens[0] && token1 == _vaultTokens[1],
"VT"
);
if (uniV3Nft != 0) {
(
, , , , , , ,
uint128 liquidity,
, ,
uint128 tokensOwed0,
uint128 tokensOwed1
) = _positionManager().positions(uniV3Nft);
require(liquidity == 0 && tokensOwed0 == 0 && tokensOwed1 == 0, "TVL");
// return previous uni v3 position nft
_positionManager().transferFrom(address(this), from, uniV3Nft);
}
uniV3Nft = tokenId;
return this.onERC721Received.selector;
}
function collectEarnings(address to) external nonReentrant returns (uint256[] memory collectedEarnings) {
require(_isApprovedOrOwner(msg.sender), ExceptionsLibrary.APPROVED_OR_OWNER);
IVaultRegistry registry = _vaultGovernance.internalParams().registry;
address owner = registry.ownerOf(_nft);
require(owner == msg.sender || _isValidPullDestination(to), ExceptionsLibrary.VALID_PULL_DESTINATION);
collectedEarnings = new uint256[](2);
(uint256 collectedEarnings0, uint256 collectedEarnings1) = _positionManager().collect(
INonfungiblePositionManager.CollectParams({
tokenId: uniV3Nft,
recipient: to,
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
collectedEarnings[0] = collectedEarnings0;
collectedEarnings[1] = collectedEarnings1;
emit CollectedEarnings(tx.origin, to, collectedEarnings0, collectedEarnings1);
}
/// @inheritdoc Vault
function tvl() public view override returns (uint256[] memory tokenAmounts) {
tokenAmounts = new uint256[](_vaultTokens.length);
if (uniV3Nft == 0)
return tokenAmounts;
(
, , , , ,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
, , ,
) = _positionManager().positions(uniV3Nft);
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
uint160 sqrtPriceAX96 = TickMath.getSqrtRatioAtTick(tickLower);
uint160 sqrtPriceBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
(uint256 amount0, uint256 amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
sqrtPriceAX96,
sqrtPriceBX96,
liquidity
);
tokenAmounts[0] = amount0;
tokenAmounts[1] = amount1;
}
function _push(uint256[] memory tokenAmounts, bytes memory options)
internal
override
returns (uint256[] memory actualTokenAmounts)
{
address[] memory tokens = _vaultTokens;
for (uint256 i = 0; i < tokens.length; i++)
_allowTokenIfNecessary(tokens[i]);
actualTokenAmounts = new uint256[](2);
if (uniV3Nft == 0)
return actualTokenAmounts;
Options memory opts = _parseOptions(options);
Pair memory amounts = Pair({
a0: tokenAmounts[0],
a1: tokenAmounts[1]
});
Pair memory minAmounts = Pair({
a0: opts.amount0Min,
a1: opts.amount1Min
});
(, uint256 amount0, uint256 amount1) = _positionManager().increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: uniV3Nft,
amount0Desired: amounts.a0,
amount1Desired: amounts.a1,
amount0Min: minAmounts.a0,
amount1Min: minAmounts.a1,
deadline: opts.deadline
})
);
actualTokenAmounts[0] = amount0;
actualTokenAmounts[1] = amount1;
}
function _pull(
address to,
uint256[] memory tokenAmounts,
bytes memory options
) internal override returns (uint256[] memory actualTokenAmounts) {
actualTokenAmounts = new uint256[](2);
if (uniV3Nft == 0)
return actualTokenAmounts;
Options memory opts = _parseOptions(options);
Pair memory amounts = _pullUniV3Nft(tokenAmounts, to, opts);
actualTokenAmounts[0] = amounts.a0;
actualTokenAmounts[1] = amounts.a1;
}
function _pullUniV3Nft(
uint256[] memory tokenAmounts,
address to,
Options memory opts
) internal returns (Pair memory) {
uint128 liquidityToPull;
// scope the code below to avoid stack-too-deep exception
{
(, , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = _positionManager().positions(uniV3Nft);
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
uint160 sqrtPriceAX96 = TickMath.getSqrtRatioAtTick(tickLower);
uint160 sqrtPriceBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
liquidityToPull = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96, sqrtPriceAX96, sqrtPriceBX96, tokenAmounts[0], tokenAmounts[1]
);
liquidityToPull = liquidity < liquidityToPull ? liquidity : liquidityToPull;
if (liquidityToPull == 0) {
return Pair({a0: 0, a1: 0});
}
}
Pair memory minAmounts = Pair({
a0: opts.amount0Min,
a1: opts.amount1Min
});
(uint256 amount0, uint256 amount1) = _positionManager().decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: uniV3Nft,
liquidity: liquidityToPull,
amount0Min: minAmounts.a0,
amount1Min: minAmounts.a1,
deadline: opts.deadline
})
);
(uint256 amount0Collected, uint256 amount1Collected) = _positionManager().collect(
INonfungiblePositionManager.CollectParams({
tokenId: uniV3Nft,
recipient: to,
amount0Max: uint128(amount0),
amount1Max: uint128(amount1)
})
);
return Pair({a0: amount0Collected, a1: amount1Collected});
}
function _postReclaimTokens(address, address[] memory tokens) internal view override {}
/// TODO: make a virtual function here? Or other better approach
function _positionManager() internal view returns (INonfungiblePositionManager) {
return IUniV3VaultGovernance(address(_vaultGovernance)).delayedProtocolParams().positionManager;
}
function _allowTokenIfNecessary(address token) internal {
if (IERC20(token).allowance(address(_positionManager()), address(this)) < type(uint256).max / 2)
IERC20(token).approve(address(_positionManager()), type(uint256).max);
}
function _parseOptions(bytes memory options) internal view returns (Options memory) {
if (options.length == 0)
return Options({amount0Min: 0, amount1Min: 0, deadline: block.timestamp + 600});
require(options.length == 32 * 3, ExceptionsLibrary.IO_LENGTH);
return abi.decode(options, (Options));
}
function _isStrategy(address addr) internal view returns (bool) {
return _vaultGovernance.internalParams().registry.getApproved(_nft) == addr;
}
event CollectedEarnings(address indexed origin, address indexed to, uint256 amount0, uint256 amount1);
} | 2,299 | 245 | 1 | 1. [H-03] UniV3Vault.sol#collectEarnings() can be front run (Front-running)
For UniV3Vault, it seems that lp fees are collected through `collectEarnings()` callable by the strategy and reinvested (rebalanced).
However, in the current implementation, unharvested yields are not included in `tvl()`, making it vulnerable to front-run attacks that steal pending yields. | 1 |
16_Pricing.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./lib/LibMath.sol";
import "./lib/LibPrices.sol";
import "./Interfaces/IPricing.sol";
import "./Interfaces/ITracerPerpetualSwaps.sol";
import "./Interfaces/IInsurance.sol";
import "./Interfaces/IOracle.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
contract Pricing is IPricing {
using LibMath for uint256;
using LibMath for int256;
using PRBMathSD59x18 for int256;
address public tracer;
IInsurance public insurance;
IOracle public oracle;
// pricing metrics
Prices.PriceInstant[24] internal hourlyTracerPrices;
Prices.PriceInstant[24] internal hourlyOraclePrices;
// funding index => funding rate
mapping(uint256 => Prices.FundingRateInstant) public fundingRates;
// funding index => insurance funding rate
mapping(uint256 => Prices.FundingRateInstant) public insuranceFundingRates;
// market's time value
int256 public override timeValue;
// funding index
uint256 public override currentFundingIndex;
// timing variables
uint256 public startLastHour;
uint256 public startLast24Hours;
uint8 public override currentHour;
event HourlyPriceUpdated(uint256 price, uint256 currentHour);
event FundingRateUpdated(int256 fundingRate, int256 cumulativeFundingRate);
event InsuranceFundingRateUpdated(int256 insuranceFundingRate, int256 insuranceFundingRateValue);
/**
* @dev Set tracer perps factory
* @dev ensure that oracle contract is returning WAD values. This may be done
* by wrapping the raw oracle in an adapter (see contracts/oracle)
* @param _tracer The address of the tracer this pricing contract links too
*/
constructor(
address _tracer,
address _insurance,
address _oracle
) {
tracer = _tracer;
insurance = IInsurance(_insurance);
oracle = IOracle(_oracle);
startLastHour = block.timestamp;
startLast24Hours = block.timestamp;
}
/**
* @notice Updates pricing information given a trade of a certain volume at
* a set price
* @param tradePrice the price the trade executed at
*/
function recordTrade(uint256 tradePrice) external override onlyTracer {
uint256 currentOraclePrice = oracle.latestAnswer();
if (startLastHour <= block.timestamp - 1 hours) {
// emit the old hourly average
uint256 hourlyTracerPrice = getHourlyAvgTracerPrice(currentHour);
emit HourlyPriceUpdated(hourlyTracerPrice, currentHour);
// update funding rate for the previous hour
updateFundingRate();
// update the time value
if (startLast24Hours <= block.timestamp - 24 hours) {
// Update the interest rate every 24 hours
updateTimeValue();
startLast24Hours = block.timestamp;
}
// update time metrics after all other state
startLastHour = block.timestamp;
// Check current hour and loop around if need be
if (currentHour == 23) {
currentHour = 0;
} else {
currentHour = currentHour + 1;
}
// add new pricing entry for new hour
updatePrice(tradePrice, currentOraclePrice, true);
} else {
// Update old pricing entry
updatePrice(tradePrice, currentOraclePrice, false);
}
}
/**
* @notice Updates both the latest market price and the latest underlying asset price (from an oracle) for a given tracer market given a tracer price
* and an oracle price.
* @param marketPrice The price that a tracer was bought at, returned by the TracerPerpetualSwaps.sol contract when an order is filled
* @param oraclePrice The price of the underlying asset that the Tracer is based upon as returned by a Chainlink Oracle
* @param newRecord Bool that decides if a new hourly record should be started (true) or if a current hour should be updated (false)
*/
function updatePrice(
uint256 marketPrice,
uint256 oraclePrice,
bool newRecord
) internal {
// Price records entries updated every hour
if (newRecord) {
// Make new hourly record, total = marketprice, numtrades set to 1;
Prices.PriceInstant memory newHourly = Prices.PriceInstant(marketPrice, 1);
hourlyTracerPrices[currentHour] = newHourly;
// As above but with Oracle price
Prices.PriceInstant memory oracleHour = Prices.PriceInstant(oraclePrice, 1);
hourlyOraclePrices[currentHour] = oracleHour;
} else {
// If an update is needed, add the market price to a running total and increment number of trades
hourlyTracerPrices[currentHour].cumulativePrice =
hourlyTracerPrices[currentHour].cumulativePrice +
marketPrice;
hourlyTracerPrices[currentHour].trades = hourlyTracerPrices[currentHour].trades + 1;
// As above but with oracle price
hourlyOraclePrices[currentHour].cumulativePrice =
hourlyOraclePrices[currentHour].cumulativePrice +
oraclePrice;
hourlyOraclePrices[currentHour].trades = hourlyOraclePrices[currentHour].trades + 1;
}
}
/**
* @notice Updates the funding rate and the insurance funding rate
*/
function updateFundingRate() internal {
// Get 8 hour time-weighted-average price (TWAP) and calculate the new funding rate and store it a new variable
ITracerPerpetualSwaps _tracer = ITracerPerpetualSwaps(tracer);
Prices.TWAP memory twapPrices = getTWAPs(currentHour);
int256 iPoolFundingRate = insurance.getPoolFundingRate().toInt256();
uint256 underlyingTWAP = twapPrices.underlying;
uint256 derivativeTWAP = twapPrices.derivative;
int256 newFundingRate = PRBMathSD59x18.mul(
derivativeTWAP.toInt256() - underlyingTWAP.toInt256() - timeValue,
_tracer.fundingRateSensitivity().toInt256()
);
// Create variable with value of new funding rate value
int256 currentFundingRateValue = fundingRates[currentFundingIndex].cumulativeFundingRate;
int256 cumulativeFundingRate = currentFundingRateValue + newFundingRate;
// as above but with insurance funding rate value
int256 currentInsuranceFundingRateValue = insuranceFundingRates[currentFundingIndex].cumulativeFundingRate;
int256 iPoolFundingRateValue = currentInsuranceFundingRateValue + iPoolFundingRate;
// Call setter functions on calculated variables
setFundingRate(newFundingRate, cumulativeFundingRate);
emit FundingRateUpdated(newFundingRate, cumulativeFundingRate);
setInsuranceFundingRate(iPoolFundingRate, iPoolFundingRateValue);
emit InsuranceFundingRateUpdated(iPoolFundingRate, iPoolFundingRateValue);
// increment funding index
currentFundingIndex = currentFundingIndex + 1;
}
/**
* @notice Given the address of a tracer market this function will get the current fair price for that market
*/
function fairPrice() external view override returns (uint256) {
return Prices.fairPrice(oracle.latestAnswer(), timeValue);
}
////////////////////////////
/// SETTER FUNCTIONS ///
//////////////////////////
/**
* @notice Calculates and then updates the time Value for a tracer market
*/
function updateTimeValue() internal {
(uint256 avgPrice, uint256 oracleAvgPrice) = get24HourPrices();
timeValue += Prices.timeValue(avgPrice, oracleAvgPrice);
}
/**
* @notice Sets the values of the fundingRate struct
* @param fundingRate The funding Rate of the Tracer, calculated by updateFundingRate
* @param cumulativeFundingRate The cumulativeFundingRate, incremented each time the funding rate is updated
*/
function setFundingRate(int256 fundingRate, int256 cumulativeFundingRate) internal {
fundingRates[currentFundingIndex] = Prices.FundingRateInstant(
block.timestamp,
fundingRate,
cumulativeFundingRate
);
}
/**
* @notice Sets the values of the fundingRate struct for a particular Tracer Marker
* @param fundingRate The insurance funding Rate of the Tracer, calculated by updateFundingRate
* @param cumulativeFundingRate The cumulativeFundingRate, incremented each time the funding rate is updated
*/
function setInsuranceFundingRate(int256 fundingRate, int256 cumulativeFundingRate) internal {
insuranceFundingRates[currentFundingIndex] = Prices.FundingRateInstant(
block.timestamp,
fundingRate,
cumulativeFundingRate
);
}
// todo by using public variables lots of these can be removed
/**
* @return each variable of the fundingRate struct of a particular tracer at a particular funding rate index
*/
function getFundingRate(uint256 index) external view override returns (Prices.FundingRateInstant memory) {
return fundingRates[index];
}
/**
* @return all of the variables in the funding rate struct (insurance rate) from a particular tracer market
*/
function getInsuranceFundingRate(uint256 index) external view override returns (Prices.FundingRateInstant memory) {
return insuranceFundingRates[index];
}
/**
* @notice Gets an 8 hour time weighted avg price for a given tracer, at a particular hour. More recent prices are weighted more heavily.
* @param hour An integer representing what hour of the day to collect from (0-24)
* @return the time weighted average price for both the oraclePrice (derivative price) and the Tracer Price
*/
function getTWAPs(uint256 hour) public view override returns (Prices.TWAP memory) {
return Prices.calculateTWAP(hour, hourlyTracerPrices, hourlyOraclePrices);
}
/**
* @notice Gets a 24 hour tracer and oracle price for a given tracer market
* @return the average price over a 24 hour period for oracle and Tracer price
*/
function get24HourPrices() public view override returns (uint256, uint256) {
return (Prices.averagePriceForPeriod(hourlyTracerPrices), Prices.averagePriceForPeriod(hourlyOraclePrices));
}
/**
* @notice Gets the average tracer price for a given market during a certain hour
* @param hour The hour of which you want the hourly average Price
* @return the average price of the tracer for a particular hour
*/
function getHourlyAvgTracerPrice(uint256 hour) public view override returns (uint256) {
return Prices.averagePrice(hourlyTracerPrices[hour]);
}
/**
* @notice Gets the average oracle price for a given market during a certain hour
* @param hour The hour of which you want the hourly average Price
*/
function getHourlyAvgOraclePrice(uint256 hour) external view override returns (uint256) {
return Prices.averagePrice(hourlyOraclePrices[hour]);
}
/**
* @dev Used when only valid tracers are allowed
*/
modifier onlyTracer() {
require(msg.sender == tracer, "PRC: Only Tracer");
_;
}
} | 2,497 | 274 | 0 | 1. [H-01] Wrong trading pricing calculations (Pricing calculations)
In the Pricing contract, an agent can manipulate the trading prices by spamming a high amount of trades.
now every order calls a `Pricing.recordTrade` using the arbitrary price set by the agent.
2. [H-02] Use of incorrect index leads to incorrect updation of funding rates (Funding index wrapping)
The `updateFundingRate()` function updates the funding rate and insurance funding rate. | 2 |
30_Vault.sol | // SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "./VaultToken.sol";
import "./interfaces/IManager.sol";
import "./interfaces/IController.sol";
import "./interfaces/IConverter.sol";
import "./interfaces/IVault.sol";
import "./interfaces/ExtendedIERC20.sol";
/**
* @title Vault
* @notice The vault is where users deposit and withdraw
* like-kind assets that have been added by governance.
*/
contract Vault is VaultToken, IVault {
using Address for address;
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MAX = 10000;
IManager public immutable override manager;
// Strategist-updated variables
address public override gauge;
uint256 public min;
uint256 public totalDepositCap;
event Deposit(address indexed account, uint256 amount);
event Withdraw(address indexed account, uint256 amount);
event Earn(address indexed token, uint256 amount);
/**
* @param _name The name of the vault token for depositors
* @param _symbol The symbol of the vault token for depositors
* @param _manager The address of the vault manager contract
*/
constructor(
string memory _name,
string memory _symbol,
address _manager
)
public
VaultToken(_name, _symbol)
{
manager = IManager(_manager);
min = 9500;
totalDepositCap = 10000000 ether;
}
/**
* STRATEGIST-ONLY FUNCTIONS
*/
/**
* @notice Sets the value of this vault's gauge
* @dev Allow to be unset with the zero address
* @param _gauge The address of the gauge
*/
function setGauge(
address _gauge
)
external
notHalted
onlyStrategist
{
gauge = _gauge;
}
/**
* @notice Sets the value for min
* @dev min is the minimum percent of funds to keep small withdrawals cheap
* @param _min The new min value
*/
function setMin(
uint256 _min
)
external
notHalted
onlyStrategist
{
require(_min <= MAX, "!_min");
min = _min;
}
/**
* @notice Sets the value for the totalDepositCap
* @dev totalDepositCap is the maximum amount of value that can be deposited
* to the metavault at a time
* @param _totalDepositCap The new totalDepositCap value
*/
function setTotalDepositCap(
uint256 _totalDepositCap
)
external
notHalted
onlyStrategist
{
totalDepositCap = _totalDepositCap;
}
/**
* @notice Swaps tokens held within the vault
* @param _token0 The token address to swap out
* @param _token1 The token address to to
* @param _expectedAmount The expected amount of _token1 to receive
*/
function swap(
address _token0,
address _token1,
uint256 _expectedAmount
)
external
override
notHalted
onlyStrategist
returns (uint256 _balance)
{
IConverter _converter = IConverter(IController(manager.controllers(address(this))).converter(address(this)));
_balance = IERC20(_token0).balanceOf(address(this));
IERC20(_token0).safeTransfer(address(_converter), _balance);
_balance = _converter.convert(_token0, _token1, _balance, _expectedAmount);
}
/**
* HARVESTER-ONLY FUNCTIONS
*/
/**
* @notice Sends accrued 3CRV tokens on the metavault to the controller to be deposited to strategies
*/
function earn(
address _token,
address _strategy
)
external
override
checkToken(_token)
notHalted
onlyHarvester
{
require(manager.allowedStrategies(_strategy), "!_strategy");
IController _controller = IController(manager.controllers(address(this)));
if (_controller.investEnabled()) {
uint256 _balance = available(_token);
IERC20(_token).safeTransfer(address(_controller), _balance);
_controller.earn(_strategy, _token, _balance);
emit Earn(_token, _balance);
}
}
/**
* USER-FACING FUNCTIONS
*/
/**
* @notice Deposits the given token into the vault
* @param _token The address of the token
* @param _amount The amount of tokens to deposit
*/
function deposit(
address _token,
uint256 _amount
)
public
override
checkToken(_token)
notHalted
returns (uint256 _shares)
{
require(_amount > 0, "!_amount");
uint256 _balance = balance();
uint256 _before = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
_amount = IERC20(_token).balanceOf(address(this)).sub(_before);
if (_amount > 0) {
_amount = _normalizeDecimals(_token, _amount);
if (totalSupply() > 0) {
_amount = (_amount.mul(totalSupply())).div(_balance);
}
_shares = _amount;
}
if (_shares > 0) {
_mint(msg.sender, _shares);
require(totalSupply() <= totalDepositCap, ">totalDepositCap");
emit Deposit(msg.sender, _shares);
}
}
/**
* @notice Deposits multiple tokens simultaneously to the vault
* @dev Users must approve the vault to spend their stablecoin
* @param _tokens The addresses of each token being deposited
* @param _amounts The amounts of each token being deposited
*/
function depositMultiple(
address[] calldata _tokens,
uint256[] calldata _amounts
)
external
override
returns (uint256 _shares)
{
require(_tokens.length == _amounts.length, "!length");
for (uint8 i; i < _amounts.length; i++) {
_shares = _shares.add(deposit(_tokens[i], _amounts[i]));
}
}
/**
* @notice Withdraws an amount of shares to a given output token
* @param _shares The amount of shares to withdraw
* @param _output The address of the token to receive
*/
function withdraw(
uint256 _shares,
address _output
)
public
override
checkToken(_output)
{
uint256 _amount = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
uint256 _withdrawalProtectionFee = manager.withdrawalProtectionFee();
if (_withdrawalProtectionFee > 0) {
uint256 _withdrawalProtection = _amount.mul(_withdrawalProtectionFee).div(MAX);
_amount = _amount.sub(_withdrawalProtection);
}
uint256 _balance = IERC20(_output).balanceOf(address(this));
if (_balance < _amount) {
IController _controller = IController(manager.controllers(address(this)));
uint256 _toWithdraw = _amount.sub(_balance);
if (_controller.strategies() > 0) {
_controller.withdraw(_output, _toWithdraw);
}
uint256 _after = IERC20(_output).balanceOf(address(this));
uint256 _diff = _after.sub(_balance);
if (_diff < _toWithdraw) {
_amount = _after;
}
}
IERC20(_output).safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _amount);
}
/**
* @notice Withdraw the entire balance for an account
* @param _output The address of the desired token to receive
*/
function withdrawAll(
address _output
)
external
override
{
withdraw(balanceOf(msg.sender), _output);
}
/**
* VIEWS
*/
/**
* @notice Returns the amount of tokens available to be sent to strategies
* @dev Custom logic in here for how much the vault allows to be borrowed
* @dev Sets minimum required on-hand to keep small withdrawals cheap
* @param _token The address of the token
*/
function available(
address _token
)
public
view
override
returns (uint256)
{
return IERC20(_token).balanceOf(address(this)).mul(min).div(MAX);
}
/**
* @notice Returns the total balance of the vault, including strategies
*/
function balance()
public
view
override
returns (uint256 _balance)
{
return balanceOfThis().add(IController(manager.controllers(address(this))).balanceOf());
}
/**
* @notice Returns the balance of allowed tokens present on the vault only
*/
function balanceOfThis()
public
view
returns (uint256 _balance)
{
address[] memory _tokens = manager.getTokens(address(this));
for (uint8 i; i < _tokens.length; i++) {
address _token = _tokens[i];
_balance = _balance.add(_normalizeDecimals(_token, IERC20(_token).balanceOf(address(this))));
}
}
/**
* @notice Returns the rate of vault shares
*/
function getPricePerFullShare()
external
view
override
returns (uint256)
{
if (totalSupply() > 0) {
return balance().mul(1e18).div(totalSupply());
} else {
return balance();
}
}
/**
* @notice Returns an array of the tokens for this vault
*/
function getTokens()
external
view
override
returns (address[] memory)
{
return manager.getTokens(address(this));
}
/**
* @notice Returns the fee for withdrawing the given amount
* @param _amount The amount to withdraw
*/
function withdrawFee(
uint256 _amount
)
external
view
override
returns (uint256)
{
return manager.withdrawalProtectionFee().mul(_amount).div(MAX);
}
function _normalizeDecimals(
address _token,
uint256 _amount
)
internal
view
returns (uint256)
{
uint256 _decimals = uint256(ExtendedIERC20(_token).decimals());
if (_decimals < 18) {
_amount = _amount.mul(10**(18-_decimals));
}
return _amount;
}
/**
* MODIFIERS
*/
modifier checkToken(address _token) {
require(manager.allowedTokens(_token) && manager.vaults(_token) == address(this), "!_token");
_;
}
modifier notHalted() {
require(!manager.halted(), "halted");
_;
}
modifier onlyHarvester() {
require(msg.sender == manager.harvester(), "!harvester");
_;
}
modifier onlyStrategist() {
require(msg.sender == manager.strategist(), "!strategist");
_;
}
} | 2,561 | 409 | 0 | 1. [H-05] Vault treats all tokens exactly the same that creates (huge) arbitrage opportunities.
`_shares = _shares.add(_amount);` in function `depositMultiple`
2. [H-06] earn results in decreasing share price. Function `available()`
3. [H-10] An attacker can steal funds from multi-token vaults Function `balanceOfThis()` and `balance()` | 3 |
69_NFTXSimpleFeeDistributor.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interface/INFTXLPStaking.sol";
import "./interface/INFTXSimpleFeeDistributor.sol";
import "./interface/INFTXInventoryStaking.sol";
import "./interface/INFTXVaultFactory.sol";
import "./token/IERC20Upgradeable.sol";
import "./util/SafeERC20Upgradeable.sol";
import "./util/SafeMathUpgradeable.sol";
import "./util/PausableUpgradeable.sol";
import "./util/ReentrancyGuardUpgradeable.sol";
contract NFTXSimpleFeeDistributor is INFTXSimpleFeeDistributor, ReentrancyGuardUpgradeable, PausableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
bool public distributionPaused;
address public override nftxVaultFactory;
address public override lpStaking;
address public override treasury;
// Total allocation points per vault.
uint256 public override allocTotal;
FeeReceiver[] public feeReceivers;
address public override inventoryStaking;
event UpdateTreasuryAddress(address newTreasury);
event UpdateLPStakingAddress(address newLPStaking);
event UpdateInventoryStakingAddress(address newInventoryStaking);
event UpdateNFTXVaultFactory(address factory);
event PauseDistribution(bool paused);
event AddFeeReceiver(address receiver, uint256 allocPoint);
event UpdateFeeReceiverAlloc(address receiver, uint256 allocPoint);
event UpdateFeeReceiverAddress(address oldReceiver, address newReceiver);
event RemoveFeeReceiver(address receiver);
function __SimpleFeeDistributor__init__(address _lpStaking, address _treasury) public override initializer {
__Pausable_init();
setTreasuryAddress(_treasury);
setLPStakingAddress(_lpStaking);
_addReceiver(0.8 ether, lpStaking, true);
}
function distribute(uint256 vaultId) external override virtual nonReentrant {
require(nftxVaultFactory != address(0));
address _vault = INFTXVaultFactory(nftxVaultFactory).vault(vaultId);
uint256 tokenBalance = IERC20Upgradeable(_vault).balanceOf(address(this));
if (distributionPaused || allocTotal == 0) {
IERC20Upgradeable(_vault).safeTransfer(treasury, tokenBalance);
return;
}
uint256 length = feeReceivers.length;
uint256 leftover;
for (uint256 i = 0; i < length; i++) {
FeeReceiver memory _feeReceiver = feeReceivers[i];
uint256 amountToSend = leftover + ((tokenBalance * _feeReceiver.allocPoint) / allocTotal);
uint256 currentTokenBalance = IERC20Upgradeable(_vault).balanceOf(address(this));
amountToSend = amountToSend > currentTokenBalance ? currentTokenBalance : amountToSend;
bool complete = _sendForReceiver(_feeReceiver, vaultId, _vault, amountToSend);
if (!complete) {
leftover = amountToSend;
} else {
leftover = 0;
}
}
if (leftover > 0) {
uint256 currentTokenBalance = IERC20Upgradeable(_vault).balanceOf(address(this));
IERC20Upgradeable(_vault).safeTransfer(treasury, currentTokenBalance);
}
}
function addReceiver(uint256 _allocPoint, address _receiver, bool _isContract) external override virtual onlyOwner {
_addReceiver(_allocPoint, _receiver, _isContract);
}
function initializeVaultReceivers(uint256 _vaultId) external override {
require(msg.sender == nftxVaultFactory, "FeeReceiver: not factory");
INFTXLPStaking(lpStaking).addPoolForVault(_vaultId);
if (inventoryStaking != address(0))
INFTXInventoryStaking(inventoryStaking).deployXTokenForVault(_vaultId);
}
function changeReceiverAlloc(uint256 _receiverIdx, uint256 _allocPoint) public override virtual onlyOwner {
FeeReceiver storage feeReceiver = feeReceivers[_receiverIdx];
allocTotal -= feeReceiver.allocPoint;
feeReceiver.allocPoint = _allocPoint;
allocTotal += _allocPoint;
emit UpdateFeeReceiverAlloc(feeReceiver.receiver, _allocPoint);
}
function changeReceiverAddress(uint256 _receiverIdx, address _address, bool _isContract) public override virtual onlyOwner {
FeeReceiver storage feeReceiver = feeReceivers[_receiverIdx];
address oldReceiver = feeReceiver.receiver;
feeReceiver.receiver = _address;
feeReceiver.isContract = _isContract;
emit UpdateFeeReceiverAddress(oldReceiver, _address);
}
function removeReceiver(uint256 _receiverIdx) external override virtual onlyOwner {
uint256 arrLength = feeReceivers.length;
require(_receiverIdx < arrLength, "FeeDistributor: Out of bounds");
emit RemoveFeeReceiver(feeReceivers[_receiverIdx].receiver);
allocTotal -= feeReceivers[_receiverIdx].allocPoint;
// Copy the last element to what is being removed and remove the last element.
feeReceivers[_receiverIdx] = feeReceivers[arrLength-1];
feeReceivers.pop();
}
function setTreasuryAddress(address _treasury) public override onlyOwner {
require(_treasury != address(0), "Treasury != address(0)");
treasury = _treasury;
emit UpdateTreasuryAddress(_treasury);
}
function setLPStakingAddress(address _lpStaking) public override onlyOwner {
require(_lpStaking != address(0), "LPStaking != address(0)");
lpStaking = _lpStaking;
emit UpdateLPStakingAddress(_lpStaking);
}
function setInventoryStakingAddress(address _inventoryStaking) public override onlyOwner {
inventoryStaking = _inventoryStaking;
emit UpdateInventoryStakingAddress(_inventoryStaking);
}
function setNFTXVaultFactory(address _factory) external override onlyOwner {
nftxVaultFactory = _factory;
emit UpdateNFTXVaultFactory(_factory);
}
function pauseFeeDistribution(bool pause) external onlyOwner {
distributionPaused = pause;
emit PauseDistribution(pause);
}
function rescueTokens(address _address) external override onlyOwner {
uint256 balance = IERC20Upgradeable(_address).balanceOf(address(this));
IERC20Upgradeable(_address).safeTransfer(msg.sender, balance);
}
function _addReceiver(uint256 _allocPoint, address _receiver, bool _isContract) internal virtual {
FeeReceiver memory _feeReceiver = FeeReceiver(_allocPoint, _receiver, _isContract);
feeReceivers.push(_feeReceiver);
allocTotal += _allocPoint;
emit AddFeeReceiver(_receiver, _allocPoint);
}
function _sendForReceiver(FeeReceiver memory _receiver, uint256 _vaultId, address _vault, uint256 amountToSend) internal virtual returns (bool) {
if (_receiver.isContract) {
IERC20Upgradeable(_vault).approve(_receiver.receiver, amountToSend);
// If the receive is not properly processed, send it to the treasury instead.
bytes memory payload = abi.encodeWithSelector(INFTXLPStaking.receiveRewards.selector, _vaultId, amountToSend);
(bool success, ) = address(_receiver.receiver).call(payload);
// If the allowance has not been spent, it means we can pass it forward to next.
return success && IERC20Upgradeable(_vault).allowance(address(this), _receiver.receiver) == 0;
} else {
IERC20Upgradeable(_vault).safeTransfer(_receiver.receiver, amountToSend);
}
}
} | 1,672 | 171 | 3 | 1. [H-02] The return value of the `_sendForReceiver` function is not set, causing the receiver to receive more fees (Unchecked return values)
In the NFTXSimpleFeeDistributor.sol contract, the `distribute` function is used to distribute the fee, and the distribute function judges whether the fee is sent successfully according to the return value of the _sendForReceiver function.
2. [M-01] Missing non reentrancy modifier (Reentrancy)
3. [M-02] NFTXSimpleFeeDistributor#addReceiver: Failure to check for existing receiver
The addReceiver() function fails to check if the _receiver already exists. This could lead to the same receiver being added multiple times, which results in erroneous fee distributions.
4. [M-10] NFTXSimpleFeeDistributor._sendForReceiver doesn't return success if receiver is not a contract (Lack of input validation)
5. [M-16] Malicious receiver can make `distribute` function denial of service (DoS)
In the NFTXSimpleFeeDistributor.sol contract, the distribute function calls the _sendForReceiver function to distribute the fee | 5 |
16_Liquidation.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./lib/LibMath.sol";
import "./lib/LibLiquidation.sol";
import "./lib/LibBalances.sol";
import "./lib/LibPerpetuals.sol";
import "./Interfaces/ILiquidation.sol";
import "./Interfaces/ITrader.sol";
import "./Interfaces/ITracerPerpetualSwaps.sol";
import "./Interfaces/ITracerPerpetualsFactory.sol";
import "./Interfaces/IOracle.sol";
import "./Interfaces/IPricing.sol";
import "./Interfaces/IInsurance.sol";
/**
* Each call enforces that the contract calling the account is only updating the balance
* of the account for that contract.
*/
contract Liquidation is ILiquidation, Ownable {
using LibMath for uint256;
using LibMath for int256;
uint256 public override currentLiquidationId;
uint256 public override maxSlippage;
uint256 public override releaseTime = 15 minutes;
uint256 public override minimumLeftoverGasCostMultiplier = 10;
IPricing public pricing;
ITracerPerpetualSwaps public tracer;
address public insuranceContract;
address public fastGasOracle;
// Receipt ID => LiquidationReceipt
mapping(uint256 => LibLiquidation.LiquidationReceipt) public liquidationReceipts;
event ClaimedReceipts(address indexed liquidator, address indexed market, uint256 indexed receiptId);
event ClaimedEscrow(address indexed liquidatee, address indexed market, uint256 indexed id);
event Liquidate(
address indexed account,
address indexed liquidator,
int256 liquidationAmount,
Perpetuals.Side side,
address indexed market,
uint256 liquidationId
);
event InvalidClaimOrder(uint256 indexed receiptId);
/**
* @param _pricing Pricing.sol contract address
* @param _tracer TracerPerpetualSwaps.sol contract address
* @param _insuranceContract Insurance.sol contract address
* @param _fastGasOracle Address of the contract that implements the IOracle.sol interface
* @param _maxSlippage The maximum slippage percentage that is allowed on selling a
liquidated position. Given as a decimal WAD. e.g 5% = 0.05*10^18
*/
constructor(
address _pricing,
address _tracer,
address _insuranceContract,
address _fastGasOracle,
uint256 _maxSlippage
) Ownable() {
pricing = IPricing(_pricing);
tracer = ITracerPerpetualSwaps(_tracer);
insuranceContract = _insuranceContract;
fastGasOracle = _fastGasOracle;
maxSlippage = _maxSlippage;
}
/**
* @notice Creates a liquidation receipt for a given trader
* @param liquidator the account executing the liquidation
* @param liquidatee the account being liquidated
* @param price the price at which this liquidation event occurred
* @param escrowedAmount the amount of funds required to be locked into escrow
* by the liquidator
* @param amountLiquidated the amount of positions that were liquidated
* @param liquidationSide the side of the positions being liquidated. true for long
* false for short.
*/
function submitLiquidation(
address liquidator,
address liquidatee,
uint256 price,
uint256 escrowedAmount,
int256 amountLiquidated,
Perpetuals.Side liquidationSide
) internal {
liquidationReceipts[currentLiquidationId] = LibLiquidation.LiquidationReceipt({
tracer: address(tracer),
liquidator: liquidator,
liquidatee: liquidatee,
price: price,
time: block.timestamp,
escrowedAmount: escrowedAmount,
releaseTime: block.timestamp + releaseTime,
amountLiquidated: amountLiquidated,
escrowClaimed: false,
liquidationSide: liquidationSide,
liquidatorRefundClaimed: false
});
currentLiquidationId += 1;
}
/**
* @notice Allows a trader to claim escrowed funds after the escrow period has expired
* @param receiptId The ID number of the insurance receipt from which funds are being claimed from
*/
function claimEscrow(uint256 receiptId) public override {
LibLiquidation.LiquidationReceipt memory receipt = liquidationReceipts[receiptId];
require(!receipt.escrowClaimed, "LIQ: Escrow claimed");
require(block.timestamp > receipt.releaseTime, "LIQ: Not released");
// Mark as claimed
liquidationReceipts[receiptId].escrowClaimed = true;
// Update balance
int256 amountToReturn = receipt.escrowedAmount.toInt256();
emit ClaimedEscrow(receipt.liquidatee, receipt.tracer, receiptId);
tracer.updateAccountsOnClaim(address(0), 0, receipt.liquidatee, amountToReturn, 0);
}
/**
* @notice Returns liquidation receipt data for a given receipt id.
* @param id the receipt id to get data for
*/
function getLiquidationReceipt(uint256 id)
external
view
override
returns (LibLiquidation.LiquidationReceipt memory)
{
return liquidationReceipts[id];
}
/**
* @notice Verify that a Liquidation is valid; submits liquidation receipt if it is
* @dev Reverts if the liquidation is invalid
* @param base Amount of base in the account to be liquidated (denominated in base tokens)
* @param price Fair price of the asset (denominated in quote/base)
* @param quote Amount of quote in the account to be liquidated (denominated in quote tokens)
* @param amount Amount of tokens to be liquidated
* @param gasPrice Current gas price, denominated in gwei
* @param account Account to be liquidated
* @return Amount to be escrowed for the liquidation
*/
function verifyAndSubmitLiquidation(
int256 base,
uint256 price,
int256 quote,
int256 amount,
uint256 gasPrice,
address account
) internal returns (uint256) {
require(amount > 0, "LIQ: Liquidation amount <= 0");
require(tx.gasprice <= IOracle(fastGasOracle).latestAnswer(), "LIQ: GasPrice > FGasPrice");
Balances.Position memory pos = Balances.Position(quote, base);
uint256 gasCost = gasPrice * tracer.LIQUIDATION_GAS_COST();
int256 currentMargin = Balances.margin(pos, price);
require(
currentMargin <= 0 ||
uint256(currentMargin) < Balances.minimumMargin(pos, price, gasCost, tracer.trueMaxLeverage()),
"LIQ: Account above margin"
);
require(amount <= base.abs(), "LIQ: Liquidate Amount > Position");
// calc funds to liquidate and move to Escrow
uint256 amountToEscrow = LibLiquidation.calcEscrowLiquidationAmount(
Balances.minimumMargin(pos, price, gasCost, tracer.trueMaxLeverage()),
currentMargin,
amount,
base
);
// create a liquidation receipt
Perpetuals.Side side = base < 0 ? Perpetuals.Side.Short : Perpetuals.Side.Long;
submitLiquidation(msg.sender, account, price, amountToEscrow, amount, side);
return amountToEscrow;
}
/**
* @return true if the margin is greater than 10x liquidation gas cost (in quote tokens)
* @param updatedPosition The agent's position after being liquidated
* @param lastUpdatedGasPrice The last updated gas price of the account to be liquidated
*/
function checkPartialLiquidation(Balances.Position memory updatedPosition, uint256 lastUpdatedGasPrice)
public
view
returns (bool)
{
uint256 liquidationGasCost = tracer.LIQUIDATION_GAS_COST();
uint256 price = pricing.fairPrice();
return
LibLiquidation.partialLiquidationIsValid(
updatedPosition,
lastUpdatedGasPrice,
liquidationGasCost,
price,
minimumLeftoverGasCostMultiplier
);
}
/**
* @notice Liquidates the margin account of a particular user. A deposit is needed from the liquidator.
* Generates a liquidation receipt for the liquidator to use should they need a refund.
* @param amount The amount of tokens to be liquidated
* @param account The account that is to be liquidated.
*/
function liquidate(int256 amount, address account) external override {
/* Liquidated account's balance */
Balances.Account memory liquidatedBalance = tracer.getBalance(account);
uint256 amountToEscrow = verifyAndSubmitLiquidation(
liquidatedBalance.position.base,
pricing.fairPrice(),
liquidatedBalance.position.quote,
amount,
liquidatedBalance.lastUpdatedGasPrice,
account
);
(
int256 liquidatorQuoteChange,
int256 liquidatorBaseChange,
int256 liquidateeQuoteChange,
int256 liquidateeBaseChange
) = LibLiquidation.liquidationBalanceChanges(
liquidatedBalance.position.base,
liquidatedBalance.position.quote,
amount
);
Balances.Position memory updatedPosition = Balances.Position(
liquidatedBalance.position.quote + liquidateeQuoteChange,
liquidatedBalance.position.base + liquidateeBaseChange
);
require(
checkPartialLiquidation(updatedPosition, liquidatedBalance.lastUpdatedGasPrice),
"LIQ: leaves too little left over"
);
tracer.updateAccountsOnLiquidation(
msg.sender,
account,
liquidatorQuoteChange,
liquidatorBaseChange,
liquidateeQuoteChange,
liquidateeBaseChange,
amountToEscrow
);
emit Liquidate(
account,
msg.sender,
amount,
(liquidatedBalance.position.base < 0 ? Perpetuals.Side.Short : Perpetuals.Side.Long),
address(tracer),
currentLiquidationId - 1
);
}
/**
* @notice Calculates the number of units sold and the average price of those units by a trader
* given multiple order
* @param orders a list of orders for which the units sold is being calculated from
* @param traderContract The trader contract with which the orders were made
* @param receiptId the id of the liquidation receipt the orders are being claimed against
*/
function calcUnitsSold(
Perpetuals.Order[] memory orders,
address traderContract,
uint256 receiptId
) public override returns (uint256, uint256) {
LibLiquidation.LiquidationReceipt memory receipt = liquidationReceipts[receiptId];
uint256 unitsSold;
uint256 avgPrice;
for (uint256 i; i < orders.length; i++) {
Perpetuals.Order memory order = ITrader(traderContract).getOrder(orders[i]);
if (
order.created < receipt.time || // Order made before receipt
order.maker != receipt.liquidator || // Order made by someone who isn't liquidator
order.side == receipt.liquidationSide // Order is in same direction as liquidation
/* Order should be the opposite to the position acquired on liquidation */
) {
emit InvalidClaimOrder(receiptId);
continue;
}
if (
(receipt.liquidationSide == Perpetuals.Side.Long && order.price >= receipt.price) ||
(receipt.liquidationSide == Perpetuals.Side.Short && order.price <= receipt.price)
) {
// Liquidation position was long
// Price went up, so not a slippage order
// or
// Liquidation position was short
// Price went down, so not a slippage order
emit InvalidClaimOrder(receiptId);
continue;
}
uint256 orderFilled = ITrader(traderContract).filledAmount(order);
uint256 averageExecutionPrice = ITrader(traderContract).getAverageExecutionPrice(order);
/* order.created >= receipt.time
* && order.maker == receipt.liquidator
* && order.side != receipt.liquidationSide */
unitsSold = unitsSold + orderFilled;
avgPrice = avgPrice + (averageExecutionPrice * orderFilled);
}
// Avoid divide by 0 if no orders sold
if (unitsSold == 0) {
return (0, 0);
}
return (unitsSold, avgPrice / unitsSold);
}
/**
* @notice Marks receipts as claimed and returns the refund amount
* @param escrowId the id of the receipt created during the liquidation event
* @param orders the orders that sell the liquidated positions
* @param traderContract the address of the trader contract the selling orders were made by
*/
function calcAmountToReturn(
uint256 escrowId,
Perpetuals.Order[] memory orders,
address traderContract
) public override returns (uint256) {
LibLiquidation.LiquidationReceipt memory receipt = liquidationReceipts[escrowId];
// Validate the escrowed order was fully sold
(uint256 unitsSold, uint256 avgPrice) = calcUnitsSold(orders, traderContract, escrowId);
require(unitsSold <= uint256(receipt.amountLiquidated.abs()), "LIQ: Unit mismatch");
uint256 amountToReturn = LibLiquidation.calculateSlippage(unitsSold, maxSlippage, avgPrice, receipt);
return amountToReturn;
}
/**
* @notice Drains a certain amount from insurance pool to cover excess slippage not covered by escrow
* @param amountWantedFromInsurance How much we want to drain
* @param receipt The liquidation receipt for which we are calling on the insurance pool to cover
*/
function drainInsurancePoolOnLiquidation(
uint256 amountWantedFromInsurance,
LibLiquidation.LiquidationReceipt memory receipt
) internal returns (uint256 _amountTakenFromInsurance, uint256 _amountToGiveToClaimant) {
/*
* If there was not enough escrowed, we want to call the insurance pool to help out.
* First, check the margin of the insurance Account. If this is enough, just drain from there.
* If this is not enough, call Insurance.drainPool to get some tokens from the insurance pool.
* If drainPool is able to drain enough, drain from the new margin.
* If the margin still does not have enough after calling drainPool, we are not able to fully
* claim the receipt, only up to the amount the insurance pool allows for.
*/
Balances.Account memory insuranceBalance = tracer.getBalance(insuranceContract);
if (insuranceBalance.position.quote >= amountWantedFromInsurance.toInt256()) {
// We don't need to drain insurance contract. The balance is already in the market contract
_amountTakenFromInsurance = amountWantedFromInsurance;
} else {
// insuranceBalance.quote < amountWantedFromInsurance
if (insuranceBalance.position.quote <= 0) {
// attempt to drain entire balance that is needed from the pool
IInsurance(insuranceContract).drainPool(amountWantedFromInsurance);
} else {
// attempt to drain the required balance taking into account the insurance balance in the account contract
IInsurance(insuranceContract).drainPool(
amountWantedFromInsurance - uint256(insuranceBalance.position.quote)
);
}
Balances.Account memory updatedInsuranceBalance = tracer.getBalance(insuranceContract);
if (updatedInsuranceBalance.position.quote < amountWantedFromInsurance.toInt256()) {
// Still not enough
_amountTakenFromInsurance = uint256(updatedInsuranceBalance.position.quote);
} else {
_amountTakenFromInsurance = amountWantedFromInsurance;
}
}
_amountToGiveToClaimant = receipt.escrowedAmount + _amountTakenFromInsurance;
// Don't add any to liquidatee
}
/**
* @notice Allows a liquidator to submit a single liquidation receipt and multiple order ids. If the
* liquidator experienced slippage, will refund them a proportional amount of their deposit.
* @param receiptId Used to identify the receipt that will be claimed
* @param orders The orders that sold the liquidated position
*/
function claimReceipt(
uint256 receiptId,
Perpetuals.Order[] memory orders,
address traderContract
) external override {
// Claim the receipts from the escrow system, get back amount to return
LibLiquidation.LiquidationReceipt memory receipt = liquidationReceipts[receiptId];
require(receipt.liquidator == msg.sender, "LIQ: Liquidator mismatch");
// Mark refund as claimed
require(!receipt.liquidatorRefundClaimed, "LIQ: Already claimed");
liquidationReceipts[receiptId].liquidatorRefundClaimed = true;
liquidationReceipts[receiptId].escrowClaimed = true;
require(block.timestamp < receipt.releaseTime, "LIQ: claim time passed");
require(tracer.tradingWhitelist(traderContract), "LIQ: Trader is not whitelisted");
uint256 amountToReturn = calcAmountToReturn(receiptId, orders, traderContract);
if (amountToReturn > receipt.escrowedAmount) {
liquidationReceipts[receiptId].escrowedAmount = 0;
} else {
liquidationReceipts[receiptId].escrowedAmount = receipt.escrowedAmount - amountToReturn;
}
// Keep track of how much was actually taken out of insurance
uint256 amountTakenFromInsurance;
uint256 amountToGiveToClaimant;
uint256 amountToGiveToLiquidatee;
if (amountToReturn > receipt.escrowedAmount) {
// Need to cover some loses with the insurance contract
// Whatever is the remainder that can't be covered from escrow
uint256 amountWantedFromInsurance = amountToReturn - receipt.escrowedAmount;
(amountTakenFromInsurance, amountToGiveToClaimant) = drainInsurancePoolOnLiquidation(
amountWantedFromInsurance,
receipt
);
} else {
amountToGiveToClaimant = amountToReturn;
amountToGiveToLiquidatee = receipt.escrowedAmount - amountToReturn;
}
tracer.updateAccountsOnClaim(
receipt.liquidator,
amountToGiveToClaimant.toInt256(),
receipt.liquidatee,
amountToGiveToLiquidatee.toInt256(),
amountTakenFromInsurance.toInt256()
);
emit ClaimedReceipts(msg.sender, address(tracer), receiptId);
}
function transferOwnership(address newOwner) public override(Ownable, ILiquidation) onlyOwner {
super.transferOwnership(newOwner);
}
/**
* @notice Modifies the release time
* @param _releaseTime new release time
*/
function setReleaseTime(uint256 _releaseTime) external onlyOwner() {
releaseTime = _releaseTime;
}
/**
* @notice Modifies the value to multiply the liquidation cost by in determining
* the minimum leftover margin on partial liquidation
* @param _minimumLeftoverGasCostMultiplier The new multiplier
*/
function setMinimumLeftoverGasCostMultiplier(uint256 _minimumLeftoverGasCostMultiplier) external onlyOwner() {
minimumLeftoverGasCostMultiplier = _minimumLeftoverGasCostMultiplier;
}
/**
* @notice Modifies the max slippage
* @param _maxSlippage new max slippage
*/
function setMaxSlippage(uint256 _maxSlippage) public override onlyOwner() {
maxSlippage = _maxSlippage;
}
} | 4,346 | 474 | 1 | 1. [H-05] Insurance slippage reimbursement can be used to steal insurance fund (Front-runnig, ToD)
The Liquidation contract allows the liquidator to submit "bad" trade orders and the insurance reimburses them from the insurance fund, see `Liquidation.claimReceipt`. The function can be called with an orders array, which does not check for duplicate orders. An attacker can abuse this to make a profit by liquidating themselves, making a small bad trade and repeatedly submitting this bad trade for slippage reimbursement.
| 1 |
70_VaderPoolV2.sol | // SPDX-License-Identifier: MIT AND AGPL-3.0-or-later
pragma solidity =0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./BasePoolV2.sol";
import "../../external/libraries/FixedPoint.sol";
import "../../interfaces/shared/IERC20Extended.sol";
import "../../interfaces/dex-v2/pool/IVaderPoolV2.sol";
import "../../interfaces/dex-v2/wrapper/ILPWrapper.sol";
import "../../interfaces/dex-v2/synth/ISynthFactory.sol";
/*
* @dev Implementation of {VaderPoolV2} contract.
*
* The contract VaderPool inherits from {BasePoolV2} contract and implements
* queue system.
*
* Extends on the liquidity redeeming function by introducing the `burn` function
* that internally calls the namesake on `BasePoolV2` contract and computes the
* loss covered by the position being redeemed and returns it along with amounts
* of native and foreign assets sent.
**/
contract VaderPoolV2 is IVaderPoolV2, BasePoolV2, Ownable {
/* ========== LIBRARIES ========== */
// Used for safe token transfers
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
// The LP wrapper contract
ILPWrapper public wrapper;
// The Synth Factory
ISynthFactory public synthFactory;
// Denotes whether the queue system is active
bool public queueActive;
/* ========== CONSTRUCTOR ========== */
/*
* @dev Initialised the contract state by passing the native asset's address
* to the inherited {BasePoolV2} contract's constructor and setting queue status
* to the {queueActive} state variable.
**/
constructor(bool _queueActive, IERC20 _nativeAsset)
BasePoolV2(_nativeAsset)
{
queueActive = _queueActive;
}
/* ========== VIEWS ========== */
/*
* @dev Returns cumulative prices and the timestamp the were last updated
* for both native and foreign assets against the pair specified by
* parameter {foreignAsset}.
**/
function cumulativePrices(IERC20 foreignAsset)
public
view
returns (
uint256 price0CumulativeLast,
uint256 price1CumulativeLast,
uint32 blockTimestampLast
)
{
PriceCumulative memory priceCumulative = pairInfo[foreignAsset]
.priceCumulative;
price0CumulativeLast = priceCumulative.nativeLast;
price1CumulativeLast = priceCumulative.foreignLast;
blockTimestampLast = pairInfo[foreignAsset].blockTimestampLast;
if (blockTimestampLast < block.timestamp) {
uint256 timeElapsed = block.timestamp - blockTimestampLast;
unchecked {
price0CumulativeLast +=
uint256(
FixedPoint
.fraction(
pairInfo[foreignAsset].reserveForeign,
pairInfo[foreignAsset].reserveNative
)
._x
) *
timeElapsed;
price1CumulativeLast +=
uint256(
FixedPoint
.fraction(
pairInfo[foreignAsset].reserveNative,
pairInfo[foreignAsset].reserveForeign
)
._x
) *
timeElapsed;
}
}
}
/* ========== MUTATIVE FUNCTIONS ========== */
/*
* @dev Initializes contract's state with LP wrapper, synth factory
* and router addresses.
*
* Requirements:
* - None of the parameters are zero addresses.
* - The parameters are not already set.
* - Only callable by contract owner.
**/
function initialize(
ILPWrapper _wrapper,
ISynthFactory _synthFactory,
address _router
) external onlyOwner {
require(
wrapper == ILPWrapper(_ZERO_ADDRESS),
"VaderPoolV2::initialize: Already initialized"
);
require(
_wrapper != ILPWrapper(_ZERO_ADDRESS),
"VaderPoolV2::initialize: Incorrect Wrapper Specified"
);
require(
_synthFactory != ISynthFactory(_ZERO_ADDRESS),
"VaderPoolV2::initialize: Incorrect SynthFactory Specified"
);
require(
_router != _ZERO_ADDRESS,
"VaderPoolV2::initialize: Incorrect Router Specified"
);
wrapper = _wrapper;
synthFactory = _synthFactory;
router = _router;
}
/*
* @dev Allows minting of synthetic assets corresponding to the {foreignAsset} based
* on the native asset amount deposited and returns the minted synth asset amount.
*
* Creates the synthetic asset against {foreignAsset} if it does not already exist.
*
* Updates the cumulative prices for native and foreign assets.
*
* Requirements:
* - {foreignAsset} must be a supported token.
**/
function mintSynth(
IERC20 foreignAsset,
uint256 nativeDeposit,
address from,
address to
)
external
override
nonReentrant
supportedToken(foreignAsset)
returns (uint256 amountSynth)
{
nativeAsset.safeTransferFrom(from, address(this), nativeDeposit);
ISynth synth = synthFactory.synths(foreignAsset);
if (synth == ISynth(_ZERO_ADDRESS))
synth = synthFactory.createSynth(
IERC20Extended(address(foreignAsset))
);
(uint112 reserveNative, uint112 reserveForeign, ) = getReserves(
foreignAsset
);
// gas savings
amountSynth = VaderMath.calculateSwap(
nativeDeposit,
reserveNative,
reserveForeign
);
// TODO: Clarify
_update(
foreignAsset,
reserveNative + nativeDeposit,
reserveForeign,
reserveNative,
reserveForeign
);
synth.mint(to, amountSynth);
}
/*
* @dev Allows burning of synthetic assets corresponding to the {foreignAsset}
* and returns the redeemed amount of native asset.
*
* Updates the cumulative prices for native and foreign assets.
*
* Requirements:
* - {foreignAsset} must have a valid synthetic asset against it.
* - {synthAmount} must be greater than zero.
**/
function burnSynth(
IERC20 foreignAsset,
uint256 synthAmount,
address to
) external override nonReentrant returns (uint256 amountNative) {
ISynth synth = synthFactory.synths(foreignAsset);
require(
synth != ISynth(_ZERO_ADDRESS),
"VaderPoolV2::burnSynth: Inexistent Synth"
);
require(
synthAmount > 0,
"VaderPoolV2::burnSynth: Insufficient Synth Amount"
);
IERC20(synth).safeTransferFrom(msg.sender, address(this), synthAmount);
synth.burn(synthAmount);
(uint112 reserveNative, uint112 reserveForeign, ) = getReserves(
foreignAsset
);
// gas savings
amountNative = VaderMath.calculateSwap(
synthAmount,
reserveForeign,
reserveNative
);
// TODO: Clarify
_update(
foreignAsset,
reserveNative - amountNative,
reserveForeign,
reserveNative,
reserveForeign
);
nativeAsset.safeTransfer(to, amountNative);
}
/*
* @dev Allows burning of NFT represented by param {id} for liquidity redeeming.
*
* Deletes the position in {positions} mapping against the burned NFT token.
*
* Internally calls `_burn` function on {BasePoolV2} contract.
*
* Calculates the impermanent loss incurred by the position.
*
* Returns the amounts for native and foreign assets sent to the {to} address
* along with the covered loss.
*
* Requirements:
* - Can only be called by the Router.
**/
// NOTE: IL is only covered via router!
// NOTE: Loss is in terms of USDV
function burn(uint256 id, address to)
external
override
onlyRouter
returns (
uint256 amountNative,
uint256 amountForeign,
uint256 coveredLoss
)
{
(amountNative, amountForeign) = _burn(id, to);
Position storage position = positions[id];
uint256 creation = position.creation;
uint256 originalNative = position.originalNative;
uint256 originalForeign = position.originalForeign;
delete positions[id];
uint256 loss = VaderMath.calculateLoss(
originalNative,
originalForeign,
amountNative,
amountForeign
);
// TODO: Original Implementation Applied 100 Days
coveredLoss =
(loss * _min(block.timestamp - creation, _ONE_YEAR)) /
_ONE_YEAR;
}
/*
* @dev Allows minting of liquidity in fungible tokens. The fungible token
* is a wrapped LP token against a particular pair. The liquidity issued is also
* tracked within this contract along with liquidity issued against non-fungible
* token.
*
* Updates the cumulative prices for native and foreign assets.
*
* Calls 'mint' on the LP wrapper token contract.
*
* Requirements:
* - LP wrapper token must exist against {foreignAsset}.
**/
function mintFungible(
IERC20 foreignAsset,
uint256 nativeDeposit,
uint256 foreignDeposit,
address from,
address to
) external override nonReentrant returns (uint256 liquidity) {
IERC20Extended lp = wrapper.tokens(foreignAsset);
require(
lp != IERC20Extended(_ZERO_ADDRESS),
"VaderPoolV2::mintFungible: Unsupported Token"
);
(uint112 reserveNative, uint112 reserveForeign, ) = getReserves(
foreignAsset
);
// gas savings
nativeAsset.safeTransferFrom(from, address(this), nativeDeposit);
foreignAsset.safeTransferFrom(from, address(this), foreignDeposit);
PairInfo storage pair = pairInfo[foreignAsset];
uint256 totalLiquidityUnits = pair.totalSupply;
if (totalLiquidityUnits == 0) liquidity = nativeDeposit;
else
liquidity = VaderMath.calculateLiquidityUnits(
nativeDeposit,
reserveNative,
foreignDeposit,
reserveForeign,
totalLiquidityUnits
);
require(
liquidity > 0,
"VaderPoolV2::mintFungible: Insufficient Liquidity Provided"
);
pair.totalSupply = totalLiquidityUnits + liquidity;
_update(
foreignAsset,
reserveNative + nativeDeposit,
reserveForeign + foreignDeposit,
reserveNative,
reserveForeign
);
lp.mint(to, liquidity);
emit Mint(from, to, nativeDeposit, foreignDeposit);
}
/*
* @dev Allows burning of liquidity issued in fungible tokens.
*
* Updates the cumulative prices for native and foreign assets.
*
* Calls 'burn' on the LP wrapper token contract.
*
* Requirements:
* - LP wrapper token must exist against {foreignAsset}.
* - {amountNative} and {amountForeign} redeemed, both must be greater than zero.,
**/
function burnFungible(
IERC20 foreignAsset,
uint256 liquidity,
address to
)
external
override
nonReentrant
returns (uint256 amountNative, uint256 amountForeign)
{
IERC20Extended lp = wrapper.tokens(foreignAsset);
require(
lp != IERC20Extended(_ZERO_ADDRESS),
"VaderPoolV2::burnFungible: Unsupported Token"
);
IERC20(lp).safeTransferFrom(msg.sender, address(this), liquidity);
lp.burn(liquidity);
(uint112 reserveNative, uint112 reserveForeign, ) = getReserves(
foreignAsset
);
// gas savings
PairInfo storage pair = pairInfo[foreignAsset];
uint256 _totalSupply = pair.totalSupply;
amountNative = (liquidity * reserveNative) / _totalSupply;
amountForeign = (liquidity * reserveForeign) / _totalSupply;
require(
amountNative > 0 && amountForeign > 0,
"VaderPoolV2::burnFungible: Insufficient Liquidity Burned"
);
pair.totalSupply = _totalSupply - liquidity;
nativeAsset.safeTransfer(to, amountNative);
foreignAsset.safeTransfer(to, amountForeign);
_update(
foreignAsset,
reserveNative - amountNative,
reserveForeign - amountForeign,
reserveNative,
reserveForeign
);
emit Burn(msg.sender, amountNative, amountForeign, to);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setQueue(bool _queueActive) external override onlyOwner {
require(
_queueActive != queueActive,
"VaderPoolV2::setQueue: Already At Desired State"
);
queueActive = _queueActive;
emit QueueActive(_queueActive);
}
/*
* @dev Sets the supported state of the token represented by param {foreignAsset}.
*
* Requirements:
* - The param {foreignAsset} is not already a supported token.
**/
function setTokenSupport(
IERC20 foreignAsset,
bool support,
uint256 nativeDeposit,
uint256 foreignDeposit,
address from,
address to
) external override onlyOwner returns (uint256 liquidity) {
require(
supported[foreignAsset] != support,
"VaderPoolV2::supportToken: Already At Desired State"
);
supported[foreignAsset] = support;
if (!support) {
PairInfo storage pair = pairInfo[foreignAsset];
require(
pair.reserveNative == 0 && pair.reserveForeign == 0,
"VaderPoolV2::supportToken: Cannot Unsupport Token w/ Liquidity"
);
} else {
require(
nativeDeposit != 0 && foreignDeposit != 0,
"VaderPoolV2::supportToken: Improper First-Time Liquidity Provision"
);
liquidity = _mint(
foreignAsset,
nativeDeposit,
foreignDeposit,
from,
to
);
}
}
/*
* @dev Allows the gas throttle to be toggled on/off in case of emergency
**/
function setGasThrottle(bool _gasThrottleEnabled)
external
override
onlyOwner
{
require(
gasThrottleEnabled != _gasThrottleEnabled,
"VaderPoolV2::setGasThrottle: Already At Desired State"
);
gasThrottleEnabled = _gasThrottleEnabled;
}
/*
* @dev Sets the supported state of the token represented by param {foreignAsset}.
*
* Requirements:
* - The param {foreignAsset} is not already a supported token.
**/
function setFungibleTokenSupport(IERC20 foreignAsset)
external
override
onlyOwner
{
wrapper.createWrapper(foreignAsset);
}
/* ========== INTERNAL FUNCTIONS ========== */
/* ========== PRIVATE FUNCTIONS ========== */
/**
* @dev Calculates the minimum of the two values
*/
function _min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
} | 3,319 | 520 | 2 | 1. [H-02] VaderPoolV2 owner can steal all user assets which are approved VaderPoolV2. (Owner action, Centralization risk)
The owner of VaderPoolV2 can call the `setTokenSupport` function which allows the caller to supply any address from which to take the assets to provide the initial liquidity, the owner can also specify who shall receive the resulting LP NFT and so can take ownership over these assets. This call will succeed for any address which has an ERC20 approval on VaderPoolV2 for USDV and foreignAsset.
2. H-06: LPs of VaderPoolV2 can manipulate pool reserves to extract funds from the reserve. L265
In VaderPoolV2.burn we calculate the current losses that the LP has made to impermanent loss
3. [H-07] Redemption value of synths can be manipulated to drain VaderPoolV2 of all native assets in the associated pair.
`VaderPool.mintSynth` function
4. [H-12] Using single total native reserve variable for synth and non-synth reserves of VaderPoolV2 can lead to losses for synth holders
5. [H-14] Denial of service. (DoS)
In `mintFungible` function`
6. [M-01] VaderPoolV2.mintFungible exposes users to unlimited slippage (Front-running)
Frontrunners can extract up to 100% of the value provided by LPs to VaderPoolV2 as fungible liquidity. | 6 |
3_IncentiveDistribution.sol | // SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./RoleAware.sol";
import "./Fund.sol";
struct Claim {
uint256 startingRewardRateFP;
uint256 amount;
uint256 intraDayGain;
uint256 intraDayLoss;
}
/// @title Manage distribution of liquidity stake incentives
/// Some efforts have been made to reduce gas cost at claim time
/// and shift gas burden onto those who would want to withdraw
contract IncentiveDistribution is RoleAware, Ownable {
// fixed point number factor
uint256 internal constant FP32 = 2**32;
// the amount of contraction per thousand, per day
// of the overal daily incentive distribution
// https://en.wikipedia.org/wiki/Per_mil
uint256 public constant contractionPerMil = 999;
address public immutable MFI;
constructor(
address _MFI,
uint256 startingDailyDistributionWithoutDecimals,
address _roles
) RoleAware(_roles) Ownable() {
MFI = _MFI;
currentDailyDistribution =
startingDailyDistributionWithoutDecimals *
(1 ether);
}
// how much is going to be distributed, contracts every day
uint256 public currentDailyDistribution;
uint256 public trancheShareTotal;
uint256[] public allTranches;
struct TrancheMeta {
// portion of daily distribution per each tranche
uint256 rewardShare;
uint256 currentDayGains;
uint256 currentDayLosses;
uint256 tomorrowOngoingTotals;
uint256 yesterdayOngoingTotals;
// aggregate all the unclaimed intra-days
uint256 intraDayGains;
uint256 intraDayLosses;
uint256 intraDayRewardGains;
uint256 intraDayRewardLosses;
// how much each claim unit would get if they had staked from the dawn of time
// expressed as fixed point number
// claim amounts are expressed relative to this ongoing aggregate
uint256 aggregateDailyRewardRateFP;
uint256 yesterdayRewardRateFP;
mapping(address => Claim) claims;
}
mapping(uint256 => TrancheMeta) public trancheMetadata;
// last updated day
uint256 public lastUpdatedDay;
mapping(address => uint256) public accruedReward;
/// Set share of tranche
function setTrancheShare(uint256 tranche, uint256 share)
external
onlyOwner
{
require(
trancheMetadata[tranche].rewardShare > 0,
"Tranche is not initialized, please initialize first"
);
_setTrancheShare(tranche, share);
}
function _setTrancheShare(uint256 tranche, uint256 share) internal {
TrancheMeta storage tm = trancheMetadata[tranche];
if (share > tm.rewardShare) {
trancheShareTotal += share - tm.rewardShare;
} else {
trancheShareTotal -= tm.rewardShare - share;
}
tm.rewardShare = share;
}
/// Initialize tranche
function initTranche(uint256 tranche, uint256 share) external onlyOwner {
TrancheMeta storage tm = trancheMetadata[tranche];
require(tm.rewardShare == 0, "Tranche already initialized");
_setTrancheShare(tranche, share);
// simply initialize to 1.0
tm.aggregateDailyRewardRateFP = FP32;
allTranches.push(tranche);
}
/// Start / increase amount of claim
function addToClaimAmount(
uint256 tranche,
address recipient,
uint256 claimAmount
) external {
require(
isIncentiveReporter(msg.sender),
"Contract not authorized to report incentives"
);
if (currentDailyDistribution > 0) {
TrancheMeta storage tm = trancheMetadata[tranche];
Claim storage claim = tm.claims[recipient];
uint256 currentDay =
claimAmount * (1 days - (block.timestamp % (1 days)));
tm.currentDayGains += currentDay;
claim.intraDayGain += currentDay * currentDailyDistribution;
tm.tomorrowOngoingTotals += claimAmount * 1 days;
updateAccruedReward(tm, recipient, claim);
claim.amount += claimAmount * (1 days);
}
}
/// Decrease amount of claim
function subtractFromClaimAmount(
uint256 tranche,
address recipient,
uint256 subtractAmount
) external {
require(
isIncentiveReporter(msg.sender),
"Contract not authorized to report incentives"
);
uint256 currentDay = subtractAmount * (block.timestamp % (1 days));
TrancheMeta storage tm = trancheMetadata[tranche];
Claim storage claim = tm.claims[recipient];
tm.currentDayLosses += currentDay;
claim.intraDayLoss += currentDay * currentDailyDistribution;
tm.tomorrowOngoingTotals -= subtractAmount * 1 days;
updateAccruedReward(tm, recipient, claim);
claim.amount -= subtractAmount * (1 days);
}
function updateAccruedReward(
TrancheMeta storage tm,
address recipient,
Claim storage claim
) internal returns (uint256 rewardDelta){
if (claim.startingRewardRateFP > 0) {
rewardDelta = calcRewardAmount(tm, claim);
accruedReward[recipient] += rewardDelta;
}
// don't reward for current day (approximately)
claim.startingRewardRateFP =
tm.yesterdayRewardRateFP +
tm.aggregateDailyRewardRateFP;
}
/// @dev additional reward accrued since last update
function calcRewardAmount(TrancheMeta storage tm, Claim storage claim)
internal
view
returns (uint256 rewardAmount)
{
uint256 ours = claim.startingRewardRateFP;
uint256 aggregate = tm.aggregateDailyRewardRateFP;
if (aggregate > ours) {
rewardAmount = (claim.amount * (aggregate - ours)) / FP32;
}
}
function applyIntraDay(
TrancheMeta storage tm,
Claim storage claim
) internal view returns (uint256 gainImpact, uint256 lossImpact) {
uint256 gain = claim.intraDayGain;
uint256 loss = claim.intraDayLoss;
if (gain + loss > 0) {
gainImpact =
(gain * tm.intraDayRewardGains) /
(tm.intraDayGains + 1);
lossImpact =
(loss * tm.intraDayRewardLosses) /
(tm.intraDayLosses + 1);
}
}
/// Get a view of reward amount
function viewRewardAmount(uint256 tranche, address claimant)
external
view
returns (uint256)
{
TrancheMeta storage tm = trancheMetadata[tranche];
Claim storage claim = tm.claims[claimant];
uint256 rewardAmount =
accruedReward[claimant] + calcRewardAmount(tm, claim);
(uint256 gainImpact, uint256 lossImpact) = applyIntraDay(tm, claim);
return rewardAmount + gainImpact - lossImpact;
}
/// Withdraw current reward amount
function withdrawReward(uint256[] calldata tranches)
external
returns (uint256 withdrawAmount)
{
require(
isIncentiveReporter(msg.sender),
"Contract not authorized to report incentives"
);
updateDayTotals();
withdrawAmount = accruedReward[msg.sender];
for (uint256 i; tranches.length > i; i++) {
uint256 tranche = tranches[i];
TrancheMeta storage tm = trancheMetadata[tranche];
Claim storage claim = tm.claims[msg.sender];
withdrawAmount += updateAccruedReward(tm, msg.sender, claim);
(uint256 gainImpact, uint256 lossImpact) = applyIntraDay(
tm,
claim
);
withdrawAmount = withdrawAmount + gainImpact - lossImpact;
tm.intraDayGains -= claim.intraDayGain;
tm.intraDayLosses -= claim.intraDayLoss;
tm.intraDayRewardGains -= gainImpact;
tm.intraDayRewardLosses -= lossImpact;
claim.intraDayGain = 0;
}
accruedReward[msg.sender] = 0;
Fund(fund()).withdraw(MFI, msg.sender, withdrawAmount);
}
function updateDayTotals() internal {
uint256 nowDay = block.timestamp / (1 days);
uint256 dayDiff = nowDay - lastUpdatedDay;
// shrink the daily distribution for every day that has passed
for (uint256 i = 0; i < dayDiff; i++) {
_updateTrancheTotals();
currentDailyDistribution =
(currentDailyDistribution * contractionPerMil) /
1000;
lastUpdatedDay += 1;
}
}
function _updateTrancheTotals() internal {
for (uint256 i; allTranches.length > i; i++) {
uint256 tranche = allTranches[i];
TrancheMeta storage tm = trancheMetadata[tranche];
uint256 todayTotal =
tm.yesterdayOngoingTotals +
tm.currentDayGains -
tm.currentDayLosses;
uint256 todayRewardRateFP =
(FP32 * (currentDailyDistribution * tm.rewardShare)) /
trancheShareTotal /
todayTotal;
tm.yesterdayRewardRateFP = todayRewardRateFP;
tm.aggregateDailyRewardRateFP += todayRewardRateFP;
tm.intraDayGains +=
tm.currentDayGains *
currentDailyDistribution;
tm.intraDayLosses +=
tm.currentDayLosses *
currentDailyDistribution;
tm.intraDayRewardGains +=
(tm.currentDayGains * todayRewardRateFP) /
FP32;
tm.intraDayRewardLosses +=
(tm.currentDayLosses * todayRewardRateFP) /
FP32;
tm.yesterdayOngoingTotals = tm.tomorrowOngoingTotals;
tm.currentDayGains = 0;
tm.currentDayLosses = 0;
}
}
} | 2,215 | 321 | 2 | 1. [H-08] Rewards cannot be withdrawn (Fund locked)
The rewards for a recipient in IncentiveDistribution.sol are stored in the storage mapping indexed by recipient accruedReward[recipient] and the recipient is the actual margin trader account, see function `updateAccruedReward`.
2. [H-09] lastUpdatedDay not initialized (Timestamp manipulation, Improper Handling of Day Totals)
`lastUpdatedDay ` in function `updateDayTotals`
3. [H-11] Impossible to call function `withdrawReward` fails due to run out of gas (DoS, Gas limit) | 3 |
16_TracerPerpetualSwaps.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./lib/SafetyWithdraw.sol";
import "./lib/LibMath.sol";
import {Balances} from "./lib/LibBalances.sol";
import {Types} from "./Interfaces/Types.sol";
import "./lib/LibPrices.sol";
import "./lib/LibPerpetuals.sol";
import "./Interfaces/IOracle.sol";
import "./Interfaces/IInsurance.sol";
import "./Interfaces/ITracerPerpetualSwaps.sol";
import "./Interfaces/IPricing.sol";
import "./Interfaces/ITrader.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
contract TracerPerpetualSwaps is ITracerPerpetualSwaps, Ownable, SafetyWithdraw {
using LibMath for uint256;
using LibMath for int256;
using PRBMathSD59x18 for int256;
using PRBMathUD60x18 for uint256;
uint256 public constant override LIQUIDATION_GAS_COST = 63516;
address public immutable override tracerQuoteToken;
uint256 public immutable override quoteTokenDecimals;
bytes32 public immutable override marketId;
IPricing public pricingContract;
IInsurance public insuranceContract;
address public override liquidationContract;
uint256 public override feeRate;
uint256 public override fees;
address public override feeReceiver;
/* Config variables */
// The price of gas in gwei
address public override gasPriceOracle;
// The maximum ratio of notionalValue to margin
uint256 public override maxLeverage;
// WAD value. sensitivity of 1 = 1*10^18
uint256 public override fundingRateSensitivity;
// WAD value. The percentage for insurance pool holdings/pool target where deleveraging begins
uint256 public override deleveragingCliff;
/* The percentage of insurance holdings to target at which the insurance pool
funding rate changes, and lowestMaxLeverage is reached */
uint256 public override insurancePoolSwitchStage;
// The lowest value that maxLeverage can be, if insurance pool is empty.
uint256 public override lowestMaxLeverage;
// Account State Variables
mapping(address => Balances.Account) public balances;
uint256 public tvl;
uint256 public override leveragedNotionalValue;
// Trading interfaces whitelist
mapping(address => bool) public override tradingWhitelist;
event FeeReceiverUpdated(address indexed receiver);
event FeeWithdrawn(address indexed receiver, uint256 feeAmount);
event Deposit(address indexed user, uint256 indexed amount);
event Withdraw(address indexed user, uint256 indexed amount);
event Settled(address indexed account, int256 margin);
event MatchedOrders(
address indexed long,
address indexed short,
uint256 amount,
uint256 price,
bytes32 longOrderId,
bytes32 shortOrderId
);
event FailedOrders(address indexed long, address indexed short, bytes32 longOrderId, bytes32 shortOrderId);
/**
* @notice Creates a new tracer market and sets the initial funding rate of the market. Anyone
* will be able to purchase and trade tracers after this deployment.
* @param _marketId the id of the market, given as BASE/QUOTE
* @param _tracerQuoteToken the address of the token used for margin accounts (i.e. The margin token)
* @param _tokenDecimals the number of decimal places the quote token supports
* @param _gasPriceOracle the address of the contract implementing gas price oracle
* @param _maxLeverage the max leverage of the market represented as a WAD value.
* @param _fundingRateSensitivity the affect funding rate changes have on funding paid; u60.18-decimal fixed-point number (WAD value)
* @param _feeRate the fee taken on trades; WAD value. e.g. 2% fee = 0.02 * 10^18 = 2 * 10^16
* @param _feeReceiver the address of the person who can withdraw the fees from trades in this market
* @param _deleveragingCliff The percentage for insurance pool holdings/pool target where deleveraging begins.
* WAD value. e.g. 20% = 20*10^18
* @param _lowestMaxLeverage The lowest value that maxLeverage can be, if insurance pool is empty.
* @param _insurancePoolSwitchStage The percentage of insurance holdings to target at which the insurance pool
* funding rate changes, and lowestMaxLeverage is reached
*/
constructor(
bytes32 _marketId,
address _tracerQuoteToken,
uint256 _tokenDecimals,
address _gasPriceOracle,
uint256 _maxLeverage,
uint256 _fundingRateSensitivity,
uint256 _feeRate,
address _feeReceiver,
uint256 _deleveragingCliff,
uint256 _lowestMaxLeverage,
uint256 _insurancePoolSwitchStage
) Ownable() {
// don't convert to interface as we don't need to interact with the contract
tracerQuoteToken = _tracerQuoteToken;
quoteTokenDecimals = _tokenDecimals;
gasPriceOracle = _gasPriceOracle;
marketId = _marketId;
feeRate = _feeRate;
maxLeverage = _maxLeverage;
fundingRateSensitivity = _fundingRateSensitivity;
feeReceiver = _feeReceiver;
deleveragingCliff = _deleveragingCliff;
lowestMaxLeverage = _lowestMaxLeverage;
insurancePoolSwitchStage = _insurancePoolSwitchStage;
}
/**
* @notice Adjust the max leverage as insurance pool slides from 100% of target to 0% of target
*/
function trueMaxLeverage() public view override returns (uint256) {
IInsurance insurance = IInsurance(insuranceContract);
return
Perpetuals.calculateTrueMaxLeverage(
insurance.getPoolHoldings(),
insurance.getPoolTarget(),
maxLeverage,
lowestMaxLeverage,
deleveragingCliff,
insurancePoolSwitchStage
);
}
/**
* @notice Allows a user to deposit into their margin account
* @dev this contract must be an approved spender of the markets quote token on behalf of the depositer.
* @param amount The amount of quote tokens to be deposited into the Tracer Market account. This amount
* should be given in WAD format.
*/
function deposit(uint256 amount) external override {
Balances.Account storage userBalance = balances[msg.sender];
// settle outstanding payments
settle(msg.sender);
// convert the WAD amount to the correct token amount to transfer
// cast is safe since amount is a uint, and wadToToken can only
// scale down the value
uint256 rawTokenAmount = uint256(Balances.wadToToken(quoteTokenDecimals, amount).toInt256());
IERC20(tracerQuoteToken).transferFrom(msg.sender, address(this), rawTokenAmount);
// this prevents dust from being added to the user account
// eg 10^18 -> 10^8 -> 10^18 will remove lower order bits
int256 convertedWadAmount = Balances.tokenToWad(quoteTokenDecimals, rawTokenAmount);
// update user state
userBalance.position.quote = userBalance.position.quote + convertedWadAmount;
_updateAccountLeverage(msg.sender);
// update market TVL
tvl = tvl + uint256(convertedWadAmount);
emit Deposit(msg.sender, amount);
}
/**
* @notice Allows a user to withdraw from their margin account
* @dev Ensures that the users margin percent is valid after withdraw
* @param amount The amount of margin tokens to be withdrawn from the tracer market account. This amount
* should be given in WAD format
*/
function withdraw(uint256 amount) external override {
// settle outstanding payments
settle(msg.sender);
uint256 rawTokenAmount = Balances.wadToToken(quoteTokenDecimals, amount);
int256 convertedWadAmount = Balances.tokenToWad(quoteTokenDecimals, rawTokenAmount);
Balances.Account storage userBalance = balances[msg.sender];
int256 newQuote = userBalance.position.quote - convertedWadAmount;
// this may be able to be optimised
Balances.Position memory newPosition = Balances.Position(newQuote, userBalance.position.base);
require(
Balances.marginIsValid(
newPosition,
userBalance.lastUpdatedGasPrice * LIQUIDATION_GAS_COST,
pricingContract.fairPrice(),
trueMaxLeverage()
),
"TCR: Withdraw below valid Margin"
);
// update user state
userBalance.position.quote = newQuote;
_updateAccountLeverage(msg.sender);
// Safemath will throw if tvl < amount
tvl = tvl - amount;
// perform transfer
IERC20(tracerQuoteToken).transfer(msg.sender, rawTokenAmount);
emit Withdraw(msg.sender, uint256(convertedWadAmount));
}
/**
* @notice Attempt to match two orders that exist on-chain against each other
* @dev Emits a FailedOrders or MatchedOrders event based on whether the
* orders were successfully able to be matched
* @param order1 The first order
* @param order2 The second order
* @param fillAmount Amount that the two orders are being filled for
* @return Whether the two orders were able to be matched successfully
*/
function matchOrders(
Perpetuals.Order memory order1,
Perpetuals.Order memory order2,
uint256 fillAmount
) external override onlyWhitelisted returns (bool) {
bytes32 order1Id = Perpetuals.orderId(order1);
bytes32 order2Id = Perpetuals.orderId(order2);
uint256 filled1 = ITrader(msg.sender).filled(order1Id);
uint256 filled2 = ITrader(msg.sender).filled(order2Id);
uint256 executionPrice = Perpetuals.getExecutionPrice(order1, order2);
// settle accounts
// note: this can revert and hence no order events will be emitted
settle(order1.maker);
settle(order2.maker);
(Balances.Position memory newPos1, Balances.Position memory newPos2) = _executeTrade(
order1,
order2,
fillAmount,
executionPrice
);
// validate orders can match, and outcome state is valid
if (
!Perpetuals.canMatch(order1, filled1, order2, filled2) ||
!Balances.marginIsValid(
newPos1,
balances[order1.maker].lastUpdatedGasPrice * LIQUIDATION_GAS_COST,
pricingContract.fairPrice(),
trueMaxLeverage()
) ||
!Balances.marginIsValid(
newPos2,
balances[order2.maker].lastUpdatedGasPrice * LIQUIDATION_GAS_COST,
pricingContract.fairPrice(),
trueMaxLeverage()
)
) {
// emit failed to match event and return false
if (order1.side == Perpetuals.Side.Long) {
emit FailedOrders(order1.maker, order2.maker, order1Id, order2Id);
} else {
emit FailedOrders(order2.maker, order1.maker, order2Id, order1Id);
}
return false;
}
// update account states
balances[order1.maker].position = newPos1;
balances[order2.maker].position = newPos2;
// update fees
fees =
fees +
// add 2 * fees since getFeeRate returns the fee rate for a single
// side of the order. Both users were charged fees
uint256(Balances.getFee(fillAmount, executionPrice, feeRate) * 2);
// update leverage
_updateAccountLeverage(order1.maker);
_updateAccountLeverage(order2.maker);
// Update internal trade state
pricingContract.recordTrade(executionPrice);
if (order1.side == Perpetuals.Side.Long) {
emit MatchedOrders(order1.maker, order2.maker, fillAmount, executionPrice, order1Id, order2Id);
} else {
emit MatchedOrders(order2.maker, order1.maker, fillAmount, executionPrice, order2Id, order1Id);
}
return true;
}
/**
* @notice Updates account states of two accounts given two orders that are being executed
* @param order1 The first order
* @param order2 The second order
* @param fillAmount The amount that the two ordered are being filled for
* @param executionPrice The execution price of the trades
* @return The new balances of the two accounts after the trade
*/
function _executeTrade(
Perpetuals.Order memory order1,
Perpetuals.Order memory order2,
uint256 fillAmount,
uint256 executionPrice
) internal view returns (Balances.Position memory, Balances.Position memory) {
// Retrieve account state
Balances.Account memory account1 = balances[order1.maker];
Balances.Account memory account2 = balances[order2.maker];
// Construct `Trade` types suitable for use with LibBalances
(Balances.Trade memory trade1, Balances.Trade memory trade2) = (
Balances.Trade(executionPrice, fillAmount, order1.side),
Balances.Trade(executionPrice, fillAmount, order2.side)
);
// Calculate new account state
(Balances.Position memory newPos1, Balances.Position memory newPos2) = (
Balances.applyTrade(account1.position, trade1, feeRate),
Balances.applyTrade(account2.position, trade2, feeRate)
);
// return new account state
return (newPos1, newPos2);
}
/**
* @notice internal function for updating leverage. Called within the Account contract. Also
* updates the total leveraged notional value for the tracer market itself.
*/
function _updateAccountLeverage(address account) internal {
Balances.Account memory userBalance = balances[account];
uint256 originalLeverage = userBalance.totalLeveragedValue;
uint256 newLeverage = Balances.leveragedNotionalValue(userBalance.position, pricingContract.fairPrice());
balances[account].totalLeveragedValue = newLeverage;
// Update market leveraged notional value
_updateTracerLeverage(newLeverage, originalLeverage);
}
/**
* @notice Updates the global leverage value given an accounts new leveraged value and old leveraged value
* @param accountNewLeveragedNotional The future notional value of the account
* @param accountOldLeveragedNotional The stored notional value of the account
*/
function _updateTracerLeverage(uint256 accountNewLeveragedNotional, uint256 accountOldLeveragedNotional) internal {
leveragedNotionalValue = Prices.globalLeverage(
leveragedNotionalValue,
accountOldLeveragedNotional,
accountNewLeveragedNotional
);
}
/**
* @notice When a liquidation occurs, Liquidation.sol needs to push this contract to update
* account states as necessary.
* @param liquidator Address of the account that called liquidate(...)
* @param liquidatee Address of the under-margined account getting liquidated
* @param liquidatorQuoteChange Amount the liquidator's quote is changing
* @param liquidatorBaseChange Amount the liquidator's base is changing
* @param liquidateeQuoteChange Amount the liquidated account's quote is changing
* @param liquidateeBaseChange Amount the liquidated account's base is changing
* @param amountToEscrow The amount the liquidator has to put into escrow
*/
function updateAccountsOnLiquidation(
address liquidator,
address liquidatee,
int256 liquidatorQuoteChange,
int256 liquidatorBaseChange,
int256 liquidateeQuoteChange,
int256 liquidateeBaseChange,
uint256 amountToEscrow
) external override onlyLiquidation {
// Limits the gas use when liquidating
uint256 gasPrice = IOracle(gasPriceOracle).latestAnswer();
// Update liquidators last updated gas price
Balances.Account storage liquidatorBalance = balances[liquidator];
Balances.Account storage liquidateeBalance = balances[liquidatee];
// update liquidators balance
liquidatorBalance.lastUpdatedGasPrice = gasPrice;
liquidatorBalance.position.quote =
liquidatorBalance.position.quote +
liquidatorQuoteChange -
amountToEscrow.toInt256();
liquidatorBalance.position.base = liquidatorBalance.position.base + liquidatorBaseChange;
// update liquidatee balance
liquidateeBalance.position.quote = liquidateeBalance.position.quote + liquidateeQuoteChange;
liquidateeBalance.position.base = liquidateeBalance.position.base + liquidateeBaseChange;
// Checks if the liquidator is in a valid position to process the liquidation
require(userMarginIsValid(liquidator), "TCR: Liquidator under min margin");
}
/**
* @notice When a liquidation receipt is claimed by the liquidator (i.e. they experienced slippage),
Liquidation.sol needs to tell the market to update its balance and the balance of the
liquidated agent.
* @dev Gives the leftover amount from the receipt to the liquidated agent
* @param claimant The liquidator, who has experienced slippage selling the liquidated position
* @param amountToGiveToClaimant The amount the liquidator is owe based off slippage
* @param liquidatee The account that originally got liquidated
* @param amountToGiveToLiquidatee Amount owed to the liquidated account
* @param amountToTakeFromInsurance Amount that needs to be taken from the insurance pool
in order to cover liquidation
*/
function updateAccountsOnClaim(
address claimant,
int256 amountToGiveToClaimant,
address liquidatee,
int256 amountToGiveToLiquidatee,
int256 amountToTakeFromInsurance
) external override onlyLiquidation {
address insuranceAddr = address(insuranceContract);
balances[insuranceAddr].position.quote = balances[insuranceAddr].position.quote - amountToTakeFromInsurance;
balances[claimant].position.quote = balances[claimant].position.quote + amountToGiveToClaimant;
balances[liquidatee].position.quote = balances[liquidatee].position.quote + amountToGiveToLiquidatee;
require(balances[insuranceAddr].position.quote >= 0, "TCR: Insurance not funded enough");
}
/**
* @notice settles an account. Compares current global rate with the users last updated rate
* Updates the accounts margin balance accordingly.
* @dev Ensures the account remains in a valid margin position. Will throw if account is under margin
* and the account must then be liquidated.
* @param account the address to settle.
* @dev This function aggregates data to feed into account.sols settle function which sets
*/
function settle(address account) public override {
// Get account and global last updated indexes
uint256 accountLastUpdatedIndex = balances[account].lastUpdatedIndex;
uint256 currentGlobalFundingIndex = pricingContract.currentFundingIndex();
Balances.Account storage accountBalance = balances[account];
// if this user has no positions, bring them in sync
if (accountBalance.position.base == 0) {
// set to the last fully established index
accountBalance.lastUpdatedIndex = currentGlobalFundingIndex;
accountBalance.lastUpdatedGasPrice = IOracle(gasPriceOracle).latestAnswer();
} else if (accountLastUpdatedIndex + 1 < currentGlobalFundingIndex) {
// Only settle account if its last updated index was before the last established
// global index this is since we reference the last global index
// Get current and global funding statuses
uint256 lastEstablishedIndex = currentGlobalFundingIndex - 1;
// Note: global rates reference the last fully established rate (hence the -1), and not
// the current global rate. User rates reference the last saved user rate
Prices.FundingRateInstant memory currGlobalRate = pricingContract.getFundingRate(lastEstablishedIndex);
Prices.FundingRateInstant memory currUserRate = pricingContract.getFundingRate(accountLastUpdatedIndex);
Prices.FundingRateInstant memory currInsuranceGlobalRate = pricingContract.getInsuranceFundingRate(
lastEstablishedIndex
);
Prices.FundingRateInstant memory currInsuranceUserRate = pricingContract.getInsuranceFundingRate(
accountLastUpdatedIndex
);
// settle the account
Balances.Account storage insuranceBalance = balances[address(insuranceContract)];
accountBalance.position = Prices.applyFunding(accountBalance.position, currGlobalRate, currUserRate);
// Update account gas price
accountBalance.lastUpdatedGasPrice = IOracle(gasPriceOracle).latestAnswer();
if (accountBalance.totalLeveragedValue > 0) {
(Balances.Position memory newUserPos, Balances.Position memory newInsurancePos) = Prices.applyInsurance(
accountBalance.position,
insuranceBalance.position,
currInsuranceGlobalRate,
currInsuranceUserRate,
accountBalance.totalLeveragedValue
);
balances[account].position = newUserPos;
balances[(address(insuranceContract))].position = newInsurancePos;
}
// Update account index
accountBalance.lastUpdatedIndex = lastEstablishedIndex;
require(userMarginIsValid(account), "TCR: Target under-margined");
emit Settled(account, accountBalance.position.quote);
}
}
/**
* @notice Checks if a given accounts margin is valid
* @param account The address of the account whose margin is to be checked
* @return true if the margin is valid or false otherwise
*/
function userMarginIsValid(address account) public view returns (bool) {
Balances.Account memory accountBalance = balances[account];
return
Balances.marginIsValid(
accountBalance.position,
accountBalance.lastUpdatedGasPrice * LIQUIDATION_GAS_COST,
pricingContract.fairPrice(),
trueMaxLeverage()
);
}
/**
* @notice Withdraws the fees taken on trades, and sends them to the designated
* fee receiver (set by the owner of the market)
* @dev Anyone can call this function, but fees are transferred to the fee receiver.
* Fees is also subtracted from the total value locked in the market because
* fees are taken out of trades that result in users' quotes being modified, and
* don't otherwise get subtracted from the tvl of the market
*/
function withdrawFees() external override {
uint256 tempFees = fees;
fees = 0;
tvl = tvl - tempFees;
// Withdraw from the account
IERC20(tracerQuoteToken).transfer(feeReceiver, tempFees);
emit FeeWithdrawn(feeReceiver, tempFees);
}
function getBalance(address account) external view override returns (Balances.Account memory) {
return balances[account];
}
function setLiquidationContract(address _liquidationContract) external override onlyOwner {
require(_liquidationContract != address(0), "address(0) given");
liquidationContract = _liquidationContract;
}
function setInsuranceContract(address insurance) external override onlyOwner {
require(insurance != address(0), "address(0) given");
insuranceContract = IInsurance(insurance);
}
function setPricingContract(address pricing) external override onlyOwner {
require(pricing != address(0), "address(0) given");
pricingContract = IPricing(pricing);
}
function setGasOracle(address _gasOracle) external override onlyOwner {
require(_gasOracle != address(0), "address(0) given");
gasPriceOracle = _gasOracle;
}
function setFeeReceiver(address _feeReceiver) external override onlyOwner {
require(_feeReceiver != address(0), "address(0) given");
feeReceiver = _feeReceiver;
emit FeeReceiverUpdated(_feeReceiver);
}
function setFeeRate(uint256 _feeRate) external override onlyOwner {
feeRate = _feeRate;
}
function setMaxLeverage(uint256 _maxLeverage) external override onlyOwner {
maxLeverage = _maxLeverage;
}
function setFundingRateSensitivity(uint256 _fundingRateSensitivity) external override onlyOwner {
fundingRateSensitivity = _fundingRateSensitivity;
}
function setDeleveragingCliff(uint256 _deleveragingCliff) external override onlyOwner {
deleveragingCliff = _deleveragingCliff;
}
function setLowestMaxLeverage(uint256 _lowestMaxLeverage) external override onlyOwner {
lowestMaxLeverage = _lowestMaxLeverage;
}
function setInsurancePoolSwitchStage(uint256 _insurancePoolSwitchStage) external override onlyOwner {
insurancePoolSwitchStage = _insurancePoolSwitchStage;
}
function transferOwnership(address newOwner) public override(Ownable, ITracerPerpetualSwaps) onlyOwner {
require(newOwner != address(0), "address(0) given");
super.transferOwnership(newOwner);
}
/**
* @notice allows the owner of a market to set the whitelisting of a trading interface address
* @dev a permissioned interface may call the matchOrders function.
* @param tradingContract the contract to have its whitelisting permissions set
* @param whitelisted the permission of the contract. If true this contract make call makeOrder
*/
function setWhitelist(address tradingContract, bool whitelisted) external onlyOwner {
tradingWhitelist[tradingContract] = whitelisted;
}
// Modifier such that only the set liquidation contract can call a function
modifier onlyLiquidation() {
require(msg.sender == liquidationContract, "TCR: Sender not liquidation");
_;
}
// Modifier such that only a whitelisted trader can call a function
modifier onlyWhitelisted() {
require(tradingWhitelist[msg.sender], "TCR: Contract not whitelisted");
_;
}
} | 5,870 | 599 | 1 | 1. [H-04] Logic error in fee subtraction. L272
In `LibBalances.applyTrade()`, we need to collect a fee from the trade. However, the current code subtracts a fee from the short position and adds it to the long. The correct implementation is to subtract a fee to both (see TracerPerpetualSwaps.sol L272). This issue causes withdrawals problems, since Tracer thinks it can withdraw the collect fees, leaving the users with an incorrect amount of quote tokens.
2. [M-02] No check transferFrom() return value (Unchecked return values)
The smart contract doesn't check the return value of `token.transfer()` and `token.transferFrom()`, some erc20 token might not revert in case of error but return false. In the TracerPerpetualSwaps:deposit and Insurance:deposit this would allow a user to deposit for free. See issue page for other places.
3. [M-03] Deflationary tokens are not supported
The `deposit()` functions of Insurance and TracerPerpetualSwaps assume that the external ERC20 balance of the contract increases by the same amount as the amount parameter of the transferFrom.
4. [M-08] Missing events for critical parameter changing operations by owner (Centralization risks)
The owner of TracerPerpetualSwaps contract, who is potentially untrusted as per specification, can change the market critical parameters such as the addresses of the `Liquidation/Pricing/Insurance/GasOracle/FeeReceiver` and also critical values such as feeRate, maxLeverage, fundingRateSensitivity, deleveragingCliff, lowestMaxLeverage, insurancePoolSwitchStage and whitelisting.
5. [M-09] Wrong funding index in `settle` when no base?
The `TracerPerpetualSwaps.settle` function updates the user's last index to `currentGlobalFundingIndex`, however a comment states | 5 |
26_RCFactory.sol | pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
import "hardhat/console.sol";
import "./interfaces/IRCFactory.sol";
import "./interfaces/IRCTreasury.sol";
import "./interfaces/IRCMarket.sol";
import "./interfaces/IRCNftHubL2.sol";
import "./interfaces/IRCOrderbook.sol";
import "./lib/NativeMetaTransaction.sol";
import "./interfaces/IRealitio.sol";
contract RCFactory is Ownable, NativeMetaTransaction, IRCFactory {
IRCTreasury public override treasury;
IRCNftHubL2 public override nfthub;
IRCOrderbook public override orderbook;
IRealitio public realitio;
address public referenceContractAddress;
uint256 public referenceContractVersion;
mapping(uint256 => address[]) public marketAddresses;
mapping(address => bool) public mappingOfMarkets;
uint256[5] public potDistribution;
uint256 public sponsorshipRequired;
uint256 public override minimumPriceIncreasePercent;
uint32 public advancedWarning;
uint32 public maximumDuration;
mapping(address => bool) public governors;
bool public marketCreationGovernorsOnly = true;
bool public approvedAffilliatesOnly = true;
bool public approvedArtistsOnly = true;
bool public override trapIfUnapproved = true;
address public uberOwner;
uint256 public override maxRentIterations;
address public arbitrator;
uint32 public timeout;
mapping(address => bool) public override isMarketApproved;
mapping(address => bool) public isArtistApproved;
mapping(address => bool) public isAffiliateApproved;
mapping(address => bool) public isCardAffiliateApproved;
uint256 public nftMintingLimit;
uint256 public totalNftMintCount;
event LogMarketCreated1(
address contractAddress,
address treasuryAddress,
address nftHubAddress,
uint256 referenceContractVersion
);
event LogMarketCreated2(
address contractAddress,
uint32 mode,
string[] tokenURIs,
string ipfsHash,
uint32[] timestamps,
uint256 totalNftMintCount
);
event LogMarketApproved(address market, bool hidden);
event LogAdvancedWarning(uint256 _newAdvancedWarning);
event LogMaximumDuration(uint256 _newMaximumDuration);
constructor(
IRCTreasury _treasuryAddress,
address _realitioAddress,
address _arbitratorAddress
) {
require(address(_treasuryAddress) != address(0));
_initializeEIP712("RealityCardsFactory", "1");
uberOwner = msgSender();
treasury = _treasuryAddress;
setPotDistribution(20, 0, 0, 20, 100);
setminimumPriceIncreasePercent(10);
setNFTMintingLimit(60);
setMaxRentIterations(35);
setArbitrator(_arbitratorAddress);
setRealitioAddress(_realitioAddress);
setTimeout(86400);
}
function getMostRecentMarket(uint256 _mode)
external
view
returns (address)
{
return marketAddresses[_mode][marketAddresses[_mode].length - (1)];
}
function getAllMarkets(uint256 _mode)
external
view
returns (address[] memory)
{
return marketAddresses[_mode];
}
function getPotDistribution()
external
view
override
returns (uint256[5] memory)
{
return potDistribution;
}
modifier onlyGovernors() {
require(
governors[msgSender()] || owner() == msgSender(),
"Not approved"
);
_;
}
function setNftHubAddress(IRCNftHubL2 _newAddress, uint256 _newNftMintCount)
external
onlyOwner
{
require(address(_newAddress) != address(0));
nfthub = _newAddress;
totalNftMintCount = _newNftMintCount;
}
function setOrderbookAddress(IRCOrderbook _newAddress) external onlyOwner {
require(address(_newAddress) != address(0));
orderbook = _newAddress;
}
function setPotDistribution(
uint256 _artistCut,
uint256 _winnerCut,
uint256 _creatorCut,
uint256 _affiliateCut,
uint256 _cardAffiliateCut
) public onlyOwner {
require(
_artistCut +
_winnerCut +
_creatorCut +
_affiliateCut +
_cardAffiliateCut <=
1000,
"Cuts too big"
);
potDistribution[0] = _artistCut;
potDistribution[1] = _winnerCut;
potDistribution[2] = _creatorCut;
potDistribution[3] = _affiliateCut;
potDistribution[4] = _cardAffiliateCut;
}
function setminimumPriceIncreasePercent(uint256 _percentIncrease)
public
override
onlyOwner
{
minimumPriceIncreasePercent = _percentIncrease;
}
function setNFTMintingLimit(uint256 _mintLimit) public override onlyOwner {
nftMintingLimit = _mintLimit;
}
function setMaxRentIterations(uint256 _rentLimit)
public
override
onlyOwner
{
maxRentIterations = _rentLimit;
}
function setRealitioAddress(address _newAddress) public onlyOwner {
require(_newAddress != address(0), "Must set an address");
realitio = IRealitio(_newAddress);
}
function setArbitrator(address _newAddress) public onlyOwner {
require(_newAddress != address(0), "Must set an address");
arbitrator = _newAddress;
}
function setTimeout(uint32 _newTimeout) public onlyOwner {
timeout = _newTimeout;
}
function changeMarketCreationGovernorsOnly() external onlyOwner {
marketCreationGovernorsOnly = !marketCreationGovernorsOnly;
}
function changeApprovedArtistsOnly() external onlyOwner {
approvedArtistsOnly = !approvedArtistsOnly;
}
function changeApprovedAffilliatesOnly() external onlyOwner {
approvedAffilliatesOnly = !approvedAffilliatesOnly;
}
function setSponsorshipRequired(uint256 _amount) external onlyOwner {
sponsorshipRequired = _amount;
}
function changeTrapCardsIfUnapproved() external onlyOwner {
trapIfUnapproved = !trapIfUnapproved;
}
function setAdvancedWarning(uint32 _newAdvancedWarning) external onlyOwner {
advancedWarning = _newAdvancedWarning;
emit LogAdvancedWarning(_newAdvancedWarning);
}
function setMaximumDuration(uint32 _newMaximumDuration) external onlyOwner {
maximumDuration = _newMaximumDuration;
emit LogMaximumDuration(_newMaximumDuration);
}
function owner()
public
view
override(IRCFactory, Ownable)
returns (address)
{
return Ownable.owner();
}
function isGovernor(address _user) external view override returns (bool) {
return governors[_user];
}
function changeGovernorApproval(address _governor) external onlyOwner {
require(_governor != address(0));
governors[_governor] = !governors[_governor];
}
function changeMarketApproval(address _market) external onlyGovernors {
require(_market != address(0));
IRCMarket _marketToApprove = IRCMarket(_market);
assert(_marketToApprove.isMarket());
isMarketApproved[_market] = !isMarketApproved[_market];
emit LogMarketApproved(_market, isMarketApproved[_market]);
}
function changeArtistApproval(address _artist) external onlyGovernors {
require(_artist != address(0));
isArtistApproved[_artist] = !isArtistApproved[_artist];
}
function changeAffiliateApproval(address _affiliate)
external
onlyGovernors
{
require(_affiliate != address(0));
isAffiliateApproved[_affiliate] = !isAffiliateApproved[_affiliate];
}
function changeCardAffiliateApproval(address _affiliate)
external
onlyGovernors
{
require(_affiliate != address(0));
isCardAffiliateApproved[_affiliate] = !isCardAffiliateApproved[
_affiliate
];
}
function setReferenceContractAddress(address _newAddress) external {
require(msgSender() == uberOwner, "Extremely Verboten");
require(_newAddress != address(0));
IRCMarket newContractVariable = IRCMarket(_newAddress);
assert(newContractVariable.isMarket());
referenceContractAddress = _newAddress;
referenceContractVersion += 1;
}
function changeUberOwner(address _newUberOwner) external {
require(msgSender() == uberOwner, "Extremely Verboten");
require(_newUberOwner != address(0));
uberOwner = _newUberOwner;
}
function createMarket(
uint32 _mode,
string memory _ipfsHash,
uint32[] memory _timestamps,
string[] memory _tokenURIs,
address _artistAddress,
address _affiliateAddress,
address[] memory _cardAffiliateAddresses,
string calldata _realitioQuestion,
uint256 _sponsorship
) external returns (address) {
address _creator = msgSender();
require(
_sponsorship >= sponsorshipRequired,
"Insufficient sponsorship"
);
treasury.checkSponsorship(_creator, _sponsorship);
if (approvedArtistsOnly) {
require(
isArtistApproved[_artistAddress] ||
_artistAddress == address(0),
"Artist not approved"
);
}
if (approvedAffilliatesOnly) {
require(
isAffiliateApproved[_affiliateAddress] ||
_affiliateAddress == address(0),
"Affiliate not approved"
);
for (uint256 i = 0; i < _cardAffiliateAddresses.length; i++) {
require(
isCardAffiliateApproved[_cardAffiliateAddresses[i]] ||
_cardAffiliateAddresses[i] == address(0),
"Card affiliate not approved"
);
}
}
if (marketCreationGovernorsOnly) {
require(governors[_creator] || owner() == _creator, "Not approved");
}
require(_timestamps.length == 3, "Incorrect number of array elements");
if (advancedWarning != 0) {
require(
_timestamps[0] >= block.timestamp,
"Market opening time not set"
);
require(
_timestamps[0] - advancedWarning > block.timestamp,
"Market opens too soon"
);
}
if (maximumDuration != 0) {
require(
_timestamps[1] < block.timestamp + maximumDuration,
"Market locks too late"
);
}
require(
_timestamps[1] + (1 weeks) > _timestamps[2] &&
_timestamps[1] <= _timestamps[2],
"Oracle resolution time error"
);
require(
_tokenURIs.length <= nftMintingLimit,
"Too many tokens to mint"
);
address _newAddress = Clones.clone(referenceContractAddress);
emit LogMarketCreated1(
_newAddress,
address(treasury),
address(nfthub),
referenceContractVersion
);
emit LogMarketCreated2(
_newAddress,
_mode,
_tokenURIs,
_ipfsHash,
_timestamps,
totalNftMintCount
);
treasury.addMarket(_newAddress);
nfthub.addMarket(_newAddress);
orderbook.addMarket(
_newAddress,
_tokenURIs.length,
minimumPriceIncreasePercent
);
marketAddresses[_mode].push(_newAddress);
mappingOfMarkets[_newAddress] = true;
IRCMarket(_newAddress).initialize({
_mode: _mode,
_timestamps: _timestamps,
_numberOfTokens: _tokenURIs.length,
_totalNftMintCount: totalNftMintCount,
_artistAddress: _artistAddress,
_affiliateAddress: _affiliateAddress,
_cardAffiliateAddresses: _cardAffiliateAddresses,
_marketCreatorAddress: _creator,
_realitioQuestion: _realitioQuestion
});
require(address(nfthub) != address(0), "Nfthub not set");
for (uint256 i = 0; i < _tokenURIs.length; i++) {
uint256 _tokenId = i + totalNftMintCount;
require(
nfthub.mint(_newAddress, _tokenId, _tokenURIs[i]),
"Nft Minting Failed"
);
}
totalNftMintCount = totalNftMintCount + _tokenURIs.length;
if (_sponsorship > 0) {
IRCMarket(_newAddress).sponsor(_creator, _sponsorship);
}
return _newAddress;
}
function getOracleSettings()
external
view
override
returns (
IRealitio,
address,
uint32
)
{
return (realitio, arbitrator, timeout);
}
} | null | null | 1 | 1. [M-05] RCFactory.createMarket() does not enforce `_timestamps` and `_timestamps` being larger than `_timestamps`, even though proper functioning requires them to be so (Timestamp manipulation, Input Validation and Error Handling) | 1 |
24_SwappableYieldSource.sol | // SPDX-License-Identifier: GPL-3.0
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "@pooltogether/yield-source-interface/contracts/IYieldSource.sol";
import "./access/AssetManager.sol";
/// @title Swappable yield source contract to allow a PoolTogether prize pool to swap between different yield sources.
/// @dev This contract adheres to the PoolTogether yield source interface.
/// @dev This contract inherits AssetManager which extends OwnableUpgradable.
/// @notice Swappable yield source for a PoolTogether prize pool that generates yield by depositing into the specified yield source.
contract SwappableYieldSource is ERC20Upgradeable, IYieldSource, AssetManager, ReentrancyGuardUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice Emitted when the swappable yield source is initialized.
/// @param yieldSource Address of yield source used to initialize this swappable yield source.
/// @param decimals Number of decimals the shares (inherited ERC20) will have. Same as underlying asset to ensure same ExchangeRates.
/// @param symbol Token symbol for the underlying ERC20 shares (eg: sysDAI).
/// @param name Token name for the underlying ERC20 shares (eg: PoolTogether Swappable Yield Source DAI).
/// @param owner Swappable yield source owner.
event SwappableYieldSourceInitialized(
IYieldSource indexed yieldSource,
uint8 decimals,
string symbol,
string name,
address indexed owner
);
/// @notice Emitted when a yield source has been successfuly set.
/// @param yieldSource Yield source address that was set.
event SwappableYieldSourceSet(
IYieldSource indexed yieldSource
);
/// @notice Emitted when funds are successfully transferred from specified yield source to current yield source.
/// @param yieldSource Yield source address that provided funds.
/// @param amount Amount of funds transferred.
event FundsTransferred(
IYieldSource indexed yieldSource,
uint256 amount
);
/// @notice Emitted when ERC20 tokens other than yield source's tokens are withdrawn from the swappable yield source.
/// @param from Address that transferred funds.
/// @param to Address that received funds.
/// @param amount Amount of tokens transferred.
/// @param token ERC20 token transferred.
event TransferredERC20(
address indexed from,
address indexed to,
uint256 amount,
IERC20Upgradeable indexed token
);
/// @notice Yield source interface.
IYieldSource public yieldSource;
/// @notice Mock Initializer to initialize implementations used by minimal proxies.
function freeze() public initializer {
//no-op
}
/// @notice Hack to determine if address passed is an actual yield source.
/// @dev If depositTokenAddressData.length is not superior to 0, then staticcall didn't return any data.
/// @param _yieldSource Yield source address to check.
function _requireYieldSource(IYieldSource _yieldSource) internal view {
require(address(_yieldSource) != address(0), "SwappableYieldSource/yieldSource-not-zero-address");
(, bytes memory depositTokenAddressData) = address(_yieldSource).staticcall(abi.encode(_yieldSource.depositToken.selector));
bool isInvalidYieldSource;
if (depositTokenAddressData.length > 0) {
(address depositTokenAddress) = abi.decode(depositTokenAddressData, (address));
isInvalidYieldSource = depositTokenAddress != address(0);
}
require(isInvalidYieldSource, "SwappableYieldSource/invalid-yield-source");
}
/// @notice Initializes the swappable yield source with the yieldSource address provided.
/// @dev We approve yieldSource to spend maxUint256 amount of depositToken (eg: DAI), to save gas for future calls.
/// @param _yieldSource Yield source address used to initialize this swappable yield source.
/// @param _decimals Number of decimals the shares (inherited ERC20) will have. Same as underlying asset to ensure same ExchangeRates.
/// @param _symbol Token symbol for the underlying ERC20 shares (eg: sysDAI).
/// @param _name Token name for the underlying ERC20 shares (eg: PoolTogether Swappable Yield Source DAI).
/// @param _owner Swappable yield source owner.
/// @return true if operation is successful.
function initialize(
IYieldSource _yieldSource,
uint8 _decimals,
string calldata _symbol,
string calldata _name,
address _owner
) public initializer returns (bool) {
_requireYieldSource(_yieldSource);
yieldSource = _yieldSource;
__Ownable_init();
require(_owner != address(0), "SwappableYieldSource/owner-not-zero-address");
transferOwnership(_owner);
__ReentrancyGuard_init();
__ERC20_init(_name, _symbol);
require(_decimals > 0, "SwappableYieldSource/decimals-gt-zero");
_setupDecimals(_decimals);
IERC20Upgradeable(_yieldSource.depositToken()).safeApprove(address(_yieldSource), type(uint256).max);
emit SwappableYieldSourceInitialized(
_yieldSource,
_decimals,
_symbol,
_name,
_owner
);
return true;
}
/// @notice Approve yieldSource to spend maxUint256 amount of depositToken (eg: DAI).
/// @dev Emergency function to re-approve max amount if approval amount dropped too low.
/// @return true if operation is successful.
function approveMaxAmount() external onlyOwner returns (bool) {
IYieldSource _yieldSource = yieldSource;
IERC20Upgradeable _depositToken = IERC20Upgradeable(_yieldSource.depositToken());
uint256 allowance = _depositToken.allowance(address(this), address(_yieldSource));
_depositToken.safeIncreaseAllowance(address(_yieldSource), type(uint256).max.sub(allowance));
return true;
}
/// @notice Calculates the number of shares that should be minted or burned when a user deposit or withdraw.
/// @param tokens Amount of tokens.
/// @return Number of shares.
function _tokenToShares(uint256 tokens) internal returns (uint256) {
uint256 shares;
uint256 _totalSupply = totalSupply();
if (_totalSupply == 0) {
shares = tokens;
} else {
// rate = tokens / shares
// shares = tokens * (totalShares / swappableYieldSourceTotalSupply)
uint256 exchangeMantissa = FixedPoint.calculateMantissa(_totalSupply, yieldSource.balanceOfToken(address(this)));
shares = FixedPoint.multiplyUintByMantissa(tokens, exchangeMantissa);
}
return shares;
}
/// @notice Calculates the number of tokens a user has in the yield source.
/// @param shares Amount of shares.
/// @return Number of tokens.
function _sharesToToken(uint256 shares) internal returns (uint256) {
uint256 tokens;
uint256 _totalSupply = totalSupply();
if (_totalSupply == 0) {
tokens = shares;
} else {
// tokens = shares * (yieldSourceTotalSupply / totalShares)
uint256 exchangeMantissa = FixedPoint.calculateMantissa(yieldSource.balanceOfToken(address(this)), _totalSupply);
tokens = FixedPoint.multiplyUintByMantissa(shares, exchangeMantissa);
}
return tokens;
}
/// @notice Mint tokens to the user.
/// @dev Shares corresponding to the number of tokens supplied are minted to user's balance.
/// @param mintAmount Amount of asset tokens to be minted.
/// @param to User whose balance will receive the tokens.
function _mintShares(uint256 mintAmount, address to) internal {
uint256 shares = _tokenToShares(mintAmount);
require(shares > 0, "SwappableYieldSource/shares-gt-zero");
_mint(to, shares);
}
/// @notice Burn shares from user's balance.
/// @dev Shares corresponding to the number of tokens withdrawn are burnt from user's balance.
/// @param burnAmount Amount of asset tokens to be burnt.
function _burnShares(uint256 burnAmount) internal {
uint256 shares = _tokenToShares(burnAmount);
_burn(msg.sender, shares);
}
/// @notice Supplies tokens to the current yield source. Allows assets to be supplied on other user's behalf using the `to` param.
/// @dev Asset tokens are supplied to the yield source, then deposited into the underlying yield source (eg: Aave, Compound, etc...).
/// @dev Shares from the yield source are minted to the swappable yield source address (this contract).
/// @dev Shares from the swappable yield source are minted to the `to` address.
/// @param amount Amount of `depositToken()` to be supplied.
/// @param to User whose balance will receive the tokens.
function supplyTokenTo(uint256 amount, address to) external override nonReentrant {
IERC20Upgradeable _depositToken = IERC20Upgradeable(yieldSource.depositToken());
_depositToken.safeTransferFrom(msg.sender, address(this), amount);
yieldSource.supplyTokenTo(amount, address(this));
_mintShares(amount, to);
}
/// @notice Returns the ERC20 asset token used for deposits.
/// @return ERC20 asset token address.
function depositToken() public view override returns (address) {
return yieldSource.depositToken();
}
/// @notice Returns the total balance in swappable tokens (eg: swsDAI).
/// @return Underlying balance of swappable tokens.
function balanceOfToken(address addr) external override returns (uint256) {
return _sharesToToken(balanceOf(addr));
}
/// @notice Redeems tokens from the current yield source.
/// @dev Shares of the swappable yield source address (this contract) are burnt from the yield source.
/// @dev Shares of the `msg.sender` address are burnt from the swappable yield source.
/// @param amount Amount of `depositToken()` to withdraw.
/// @return Actual amount of tokens that were redeemed.
function redeemToken(uint256 amount) external override nonReentrant returns (uint256) {
IERC20Upgradeable _depositToken = IERC20Upgradeable(yieldSource.depositToken());
_burnShares(amount);
uint256 redeemableBalance = yieldSource.redeemToken(amount);
_depositToken.safeTransferFrom(address(this), msg.sender, redeemableBalance);
return redeemableBalance;
}
/// @notice Determine if passed yield source is different from current yield source.
/// @param _yieldSource Yield source address to check.
function _requireDifferentYieldSource(IYieldSource _yieldSource) internal view {
require(address(_yieldSource) != address(yieldSource), "SwappableYieldSource/same-yield-source");
}
/// @notice Set new yield source.
/// @dev After setting the new yield source, we need to approve it to spend maxUint256 amount of depositToken (eg: DAI).
/// @param _newYieldSource New yield source address to set.
function _setYieldSource(IYieldSource _newYieldSource) internal {
_requireDifferentYieldSource(_newYieldSource);
require(_newYieldSource.depositToken() == yieldSource.depositToken(), "SwappableYieldSource/different-deposit-token");
yieldSource = _newYieldSource;
IERC20Upgradeable(_newYieldSource.depositToken()).safeApprove(address(_newYieldSource), type(uint256).max);
emit SwappableYieldSourceSet(_newYieldSource);
}
/// @notice Set new yield source.
/// @dev This function is only callable by the owner or asset manager.
/// @param _newYieldSource New yield source address to set.
/// @return true if operation is successful.
function setYieldSource(IYieldSource _newYieldSource) external onlyOwnerOrAssetManager returns (bool) {
_setYieldSource(_newYieldSource);
return true;
}
/// @notice Transfer funds from specified yield source to current yield source.
/// @dev We check that the `currentBalance` transferred is at least equal or superior to the `amount` requested.
/// @dev `currentBalance` can be superior to `amount` if yield has been accruing between redeeming and checking for a mathematical error.
/// @param _yieldSource Yield source address to transfer funds from.
/// @param _amount Amount of funds to transfer from passed yield source to current yield source.
function _transferFunds(IYieldSource _yieldSource, uint256 _amount) internal {
IYieldSource _currentYieldSource = yieldSource;
_yieldSource.redeemToken(_amount);
uint256 currentBalance = IERC20Upgradeable(_yieldSource.depositToken()).balanceOf(address(this));
require(_amount <= currentBalance, "SwappableYieldSource/transfer-amount-different");
_currentYieldSource.supplyTokenTo(currentBalance, address(this));
emit FundsTransferred(_yieldSource, _amount);
}
/// @notice Transfer funds from specified yield source to current yield source.
/// @dev We only verify it is a different yield source in the public function cause we already check for it in `_setYieldSource` function.
/// @param _yieldSource Yield source address to transfer funds from.
/// @param amount Amount of funds to transfer from passed yield source to current yield source.
/// @return true if operation is successful.
function transferFunds(IYieldSource _yieldSource, uint256 amount) external onlyOwnerOrAssetManager returns (bool) {
_requireDifferentYieldSource(_yieldSource);
_transferFunds(_yieldSource, amount);
return true;
}
/// @notice Swap current yield source for new yield source.
/// @dev This function is only callable by the owner or asset manager.
/// @dev We set a new yield source and then transfer funds from the now previous yield source to the new current yield source.
/// @param _newYieldSource New yield source address to set and transfer funds to.
/// @return true if operation is successful.
function swapYieldSource(IYieldSource _newYieldSource) external onlyOwnerOrAssetManager returns (bool) {
IYieldSource _currentYieldSource = yieldSource;
uint256 balance = _currentYieldSource.balanceOfToken(address(this));
_setYieldSource(_newYieldSource);
_transferFunds(_currentYieldSource, balance);
return true;
}
/// @notice Transfer ERC20 tokens other than the yield source's tokens held by this contract to the recipient address.
/// @dev This function is only callable by the owner or asset manager.
/// @param erc20Token ERC20 token to transfer.
/// @param to Recipient of the tokens.
/// @param amount Amount of tokens to transfer.
/// @return true if operation is successful.
function transferERC20(IERC20Upgradeable erc20Token, address to, uint256 amount) external onlyOwnerOrAssetManager returns (bool) {
require(address(erc20Token) != address(yieldSource), "SwappableYieldSource/yield-source-token-transfer-not-allowed");
erc20Token.safeTransfer(to, amount);
emit TransferredERC20(msg.sender, to, amount, erc20Token);
return true;
}
} | 3,524 | 330 | 1 | 1. [H-01] `onlyOwnerOrAssetManager` can swap Yield Source in SwappableYieldSource at any time, immediately rugging all funds from old yield source. (Owner actions)
The function `swapYieldSource` SwappableYieldSource.sol` L307
Can be called by the owner (deployer / initializer) or Asset Manager. The function will take all funds from the old Yield Source, and transfer them to the new Yield source. Any contract that implement the function function depositToken() external returns (address) will pass the check
2. [H-02] `redeemToken` can fail for certain tokens (Unchecked return values, ERC20 token transfers)
The `SwappableYieldSource.redeemToken` function transfers tokens from the contract back to the sender, however, it uses the `ERC20.transferFrom(address(this), msg.sender, redeemableBalance)` function for this. Some deposit token implementations might fail as transferFrom checks if the contract approved itself for the redeemableBalance instead of skipping the allowance check in case the sender is the from address.
3. [H-04] SwappableYieldSource: Missing same deposit token check in `transferFunds()`
`transferFunds()` will transfer funds from a specified yield source `_yieldSource` to the current yield source set in the contract _currentYieldSource. However, it fails to check that the deposit tokens are the same. If the specified yield source's assets are of a higher valuation, then a malicious owner or asset manager will be able to exploit and pocket the difference.
4. [M-01] Single-step process for critical ownership transfer/renounce is risky (Centralization Risk)
The SwappableYieldSource allows owners and asset managers to set/swap/transfer yield sources/funds. As such, the contract ownership plays a critical role in the protocol.
Given that `AssetManager` is derived from `Ownable`, the ownership management of this contract defaults to Ownable’s `transferOwnership()` and `renounceOwnership()` methods which are not overridden here. Such critical address transfer/renouncing in one-step is very risky because it is irrecoverable from any mistakes.
5. [M-03] Inconsistent balance when supplying transfer-on-fee or deflationary tokens. L211
The `supplyTokenTo` function of `SwappableYieldSource` assumes that `amount` of `_depositToken` is transferred to itself after calling the `safeTransferFrom` function (and thus it supplies `amount` of token to the yield source). However, this may not be true if the `_depositToken` is a transfer-on-fee token or a deflationary/rebasing token, causing the received amount to be less than the accounted amount. | 5 |
68_BasketFacet.sol | // SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../interfaces/IBasketFacet.sol";
import "../ERC20/LibERC20Storage.sol";
import "../ERC20/LibERC20.sol";
import "../shared/Reentry/ReentryProtection.sol";
import "../shared/Access/CallProtection.sol";
import "./LibBasketStorage.sol";
contract BasketFacet is ReentryProtection, CallProtection, IBasketFacet {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant MIN_AMOUNT = 10**6;
uint256 public constant MAX_ENTRY_FEE = 10**17;
// 10%
uint256 public constant MAX_EXIT_FEE = 10**17;
// 10%
uint256 public constant MAX_ANNUAL_FEE = 10**17;
// 10%
uint256 public constant HUNDRED_PERCENT = 10**18;
// Assuming a block gas limit of 12M this allows for a gas consumption per token of roughly 333k allowing 2M of overhead for addtional operations
uint256 public constant MAX_TOKENS = 30;
function addToken(address _token) external override protectedCall {
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
require(!bs.inPool[_token], "TOKEN_ALREADY_IN_POOL");
require(bs.tokens.length < MAX_TOKENS, "TOKEN_LIMIT_REACHED");
// Enforce minimum to avoid rounding errors; (Minimum value is the same as in Balancer)
require(balance(_token) >= MIN_AMOUNT, "BALANCE_TOO_SMALL");
bs.inPool[_token] = true;
bs.tokens.push(IERC20(_token));
emit TokenAdded(_token);
}
function removeToken(address _token) external override protectedCall {
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
require(bs.inPool[_token], "TOKEN_NOT_IN_POOL");
bs.inPool[_token] = false;
// remove token from array
for (uint256 i; i < bs.tokens.length; i++) {
if (address(bs.tokens[i]) == _token) {
bs.tokens[i] = bs.tokens[bs.tokens.length - 1];
bs.tokens.pop();
emit TokenRemoved(_token);
break;
}
}
}
function setEntryFee(uint256 _fee) external override protectedCall {
require(_fee <= MAX_ENTRY_FEE, "FEE_TOO_BIG");
LibBasketStorage.basketStorage().entryFee = _fee;
emit EntryFeeSet(_fee);
}
function getEntryFee() external view override returns (uint256) {
return LibBasketStorage.basketStorage().entryFee;
}
function setExitFee(uint256 _fee) external override protectedCall {
require(_fee <= MAX_EXIT_FEE, "FEE_TOO_BIG");
LibBasketStorage.basketStorage().exitFee = _fee;
emit ExitFeeSet(_fee);
}
function getExitFee() external view override returns (uint256) {
return LibBasketStorage.basketStorage().exitFee;
}
function setAnnualizedFee(uint256 _fee) external override protectedCall {
chargeOutstandingAnnualizedFee();
require(_fee <= MAX_ANNUAL_FEE, "FEE_TOO_BIG");
LibBasketStorage.basketStorage().annualizedFee = _fee;
emit AnnualizedFeeSet(_fee);
}
function getAnnualizedFee() external view override returns (uint256) {
return LibBasketStorage.basketStorage().annualizedFee;
}
function setFeeBeneficiary(address _beneficiary)
external
override
protectedCall
{
chargeOutstandingAnnualizedFee();
LibBasketStorage.basketStorage().feeBeneficiary = _beneficiary;
emit FeeBeneficiarySet(_beneficiary);
}
function getFeeBeneficiary() external view override returns (address) {
return LibBasketStorage.basketStorage().feeBeneficiary;
}
function setEntryFeeBeneficiaryShare(uint256 _share)
external
override
protectedCall
{
require(_share <= HUNDRED_PERCENT, "FEE_SHARE_TOO_BIG");
LibBasketStorage.basketStorage().entryFeeBeneficiaryShare = _share;
emit EntryFeeBeneficiaryShareSet(_share);
}
function getEntryFeeBeneficiaryShare()
external
view
override
returns (uint256)
{
return LibBasketStorage.basketStorage().entryFeeBeneficiaryShare;
}
function setExitFeeBeneficiaryShare(uint256 _share)
external
override
protectedCall
{
require(_share <= HUNDRED_PERCENT, "FEE_SHARE_TOO_BIG");
LibBasketStorage.basketStorage().exitFeeBeneficiaryShare = _share;
emit ExitFeeBeneficiaryShareSet(_share);
}
function getExitFeeBeneficiaryShare()
external
view
override
returns (uint256)
{
return LibBasketStorage.basketStorage().exitFeeBeneficiaryShare;
}
function joinPool(uint256 _amount, uint16 _referral)
external
override
noReentry
{
require(!this.getLock(), "POOL_LOCKED");
chargeOutstandingAnnualizedFee();
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
uint256 totalSupply = LibERC20Storage.erc20Storage().totalSupply;
require(
totalSupply.add(_amount) <= this.getCap(),
"MAX_POOL_CAP_REACHED"
);
uint256 feeAmount = _amount.mul(bs.entryFee).div(10**18);
for (uint256 i; i < bs.tokens.length; i++) {
IERC20 token = bs.tokens[i];
uint256 tokenAmount =
balance(address(token)).mul(_amount.add(feeAmount)).div(
totalSupply
);
require(tokenAmount != 0, "AMOUNT_TOO_SMALL");
token.safeTransferFrom(msg.sender, address(this), tokenAmount);
}
// If there is any fee that should go to the beneficiary mint it
if (
feeAmount != 0 &&
bs.entryFeeBeneficiaryShare != 0 &&
bs.feeBeneficiary != address(0)
) {
uint256 feeBeneficiaryShare =
feeAmount.mul(bs.entryFeeBeneficiaryShare).div(10**18);
if (feeBeneficiaryShare != 0) {
LibERC20.mint(bs.feeBeneficiary, feeBeneficiaryShare);
}
}
LibERC20.mint(msg.sender, _amount);
emit PoolJoined(msg.sender, _amount, _referral);
}
// Must be overwritten to withdraw from strategies
function exitPool(uint256 _amount, uint16 _referral)
external
virtual
override
noReentry
{
require(!this.getLock(), "POOL_LOCKED");
chargeOutstandingAnnualizedFee();
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
uint256 totalSupply = LibERC20Storage.erc20Storage().totalSupply;
uint256 feeAmount = _amount.mul(bs.exitFee).div(10**18);
for (uint256 i; i < bs.tokens.length; i++) {
IERC20 token = bs.tokens[i];
uint256 tokenBalance = balance(address(token));
// redeem less tokens if there is an exit fee
uint256 tokenAmount =
tokenBalance.mul(_amount.sub(feeAmount)).div(totalSupply);
require(
tokenBalance.sub(tokenAmount) >= MIN_AMOUNT,
"TOKEN_BALANCE_TOO_LOW"
);
token.safeTransfer(msg.sender, tokenAmount);
}
// If there is any fee that should go to the beneficiary mint it
if (
feeAmount != 0 &&
bs.exitFeeBeneficiaryShare != 0 &&
bs.feeBeneficiary != address(0)
) {
uint256 feeBeneficiaryShare =
feeAmount.mul(bs.exitFeeBeneficiaryShare).div(10**18);
if (feeBeneficiaryShare != 0) {
LibERC20.mint(bs.feeBeneficiary, feeBeneficiaryShare);
}
}
require(
totalSupply.sub(_amount) >= MIN_AMOUNT,
"POOL_TOKEN_BALANCE_TOO_LOW"
);
LibERC20.burn(msg.sender, _amount);
emit PoolExited(msg.sender, _amount, _referral);
}
function calcOutStandingAnnualizedFee()
public
view
override
returns (uint256)
{
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
uint256 totalSupply = LibERC20Storage.erc20Storage().totalSupply;
uint256 lastFeeClaimed = bs.lastAnnualizedFeeClaimed;
uint256 annualizedFee = bs.annualizedFee;
if (
annualizedFee == 0 ||
bs.feeBeneficiary == address(0) ||
lastFeeClaimed == 0
) {
return 0;
}
uint256 timePassed = block.timestamp.sub(lastFeeClaimed);
return
totalSupply.mul(annualizedFee).div(10**18).mul(timePassed).div(
365 days
);
}
function chargeOutstandingAnnualizedFee() public override {
uint256 outStandingFee = calcOutStandingAnnualizedFee();
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
bs.lastAnnualizedFeeClaimed = block.timestamp;
// if there is any fee to mint and the beneficiary is set
// note: feeBeneficiary is already checked in calc function
if (outStandingFee != 0) {
LibERC20.mint(bs.feeBeneficiary, outStandingFee);
}
emit FeeCharged(outStandingFee);
}
// returns true when locked
function getLock() external view override returns (bool) {
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
return bs.lockBlock == 0 || bs.lockBlock >= block.number;
}
function getTokenInPool(address _token)
external
view
override
returns (bool)
{
return LibBasketStorage.basketStorage().inPool[_token];
}
function getLockBlock() external view override returns (uint256) {
return LibBasketStorage.basketStorage().lockBlock;
}
// lock up to and including _lock blocknumber
function setLock(uint256 _lock) external override protectedCall {
LibBasketStorage.basketStorage().lockBlock = _lock;
emit LockSet(_lock);
}
function setCap(uint256 _maxCap) external override protectedCall {
LibBasketStorage.basketStorage().maxCap = _maxCap;
emit CapSet(_maxCap);
}
// Seperated balance function to allow yearn like strategies to be hooked up by inheriting from this contract and overriding
function balance(address _token) public view override returns (uint256) {
return IERC20(_token).balanceOf(address(this));
}
function getTokens() external view override returns (address[] memory) {
IERC20[] memory tokens = LibBasketStorage.basketStorage().tokens;
address[] memory result = new address[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
result[i] = address(tokens[i]);
}
return (result);
}
function getCap() external view override returns (uint256) {
return LibBasketStorage.basketStorage().maxCap;
}
function calcTokensForAmount(uint256 _amount)
external
view
override
returns (address[] memory tokens, uint256[] memory amounts)
{
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
uint256 totalSupply =
LibERC20Storage.erc20Storage().totalSupply.add(
calcOutStandingAnnualizedFee()
);
tokens = new address[](bs.tokens.length);
amounts = new uint256[](bs.tokens.length);
for (uint256 i; i < bs.tokens.length; i++) {
IERC20 token = bs.tokens[i];
uint256 tokenBalance = balance(address(token));
uint256 tokenAmount = tokenBalance.mul(_amount).div(totalSupply);
// Add entry fee
tokenAmount = tokenAmount.add(
tokenAmount.mul(bs.entryFee).div(10**18)
);
tokens[i] = address(token);
amounts[i] = tokenAmount;
}
return (tokens, amounts);
}
function calcTokensForAmountExit(uint256 _amount)
external
view
override
returns (address[] memory tokens, uint256[] memory amounts)
{
LibBasketStorage.BasketStorage storage bs =
LibBasketStorage.basketStorage();
uint256 feeAmount = _amount.mul(bs.exitFee).div(10**18);
uint256 totalSupply =
LibERC20Storage.erc20Storage().totalSupply.add(
calcOutStandingAnnualizedFee()
);
tokens = new address[](bs.tokens.length);
amounts = new uint256[](bs.tokens.length);
for (uint256 i; i < bs.tokens.length; i++) {
IERC20 token = bs.tokens[i];
uint256 tokenBalance = balance(address(token));
uint256 tokenAmount =
tokenBalance.mul(_amount.sub(feeAmount)).div(totalSupply);
tokens[i] = address(token);
amounts[i] = tokenAmount;
}
return (tokens, amounts);
}
} | 2,972 | 397 | 1 | 1. [H-01] Unused ERC20 tokens are not refunded, and can be stolen by attacker. L143-L168
Under certain circumstances, e.g. annualizedFee being minted to feeBeneficiary between the time user sent the transaction and the transaction being packed into the block and causing amounts of underlying tokens for each basketToken to decrease. It’s possible or even most certainly that there will be some leftover basket underlying tokens, as BasketFacet.sol#joinPool() will only transfer required amounts of basket tokens from Join contracts.
2. [M-04] Annualized fee APY dependence on the frequency of executing a function (Frequent API call)
The APY of the annualized fee is dependent on the frequency of the execution of the BasketFacet::chargeOutstandingAnnualizedFee(). If it is called more frequently, the compounding is more frequent and the APY is higher. For less used baskets, the APY might be lower, because the compounding will happen at lower rate.
3. [M-05] `totalSupply` may exceed LibBasketStorage.basketStorage().maxCap (Overflow)
Total supply of the token may exceed the `maxCap` introduced. This can happen when a user wants to join the pool. The check in BasketFacet::joinPool(...) includes only the base amount, without fee. Thus, if fee is on and someone will want to create as many tokens as possible, the totalSupply + _amount will be set to maxCap. The call will succeed, but new tokens were also minted as the fee for bs.feeBeneficiary if bs.entryFee and bs.entryFeeBeneficiaryShare are nonzero. Thus, the number of tokens may exceed maxCap. | 3 |
5_Vader.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
// Interfaces
import "./interfaces/iERC20.sol";
import "./interfaces/iUTILS.sol";
import "./interfaces/iUSDV.sol";
import "./interfaces/iROUTER.sol";
contract Vader is iERC20 {
// ERC-20 Parameters
string public override name; string public override symbol;
uint public override decimals; uint public override totalSupply;
// ERC-20 Mappings
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
// Parameters
bool private inited;
bool public emitting;
bool public minting;
uint _1m;
uint public baseline;
uint public emissionCurve;
uint public maxSupply;
uint public secondsPerEra;
uint public currentEra;
uint public nextEraTime;
uint public feeOnTransfer;
address public VETHER;
address public USDV;
address public UTILS;
address public burnAddress;
address public rewardAddress;
address public DAO;
event NewEra(uint currentEra, uint nextEraTime, uint emission);
// Only DAO can execute
modifier onlyDAO() {
require(msg.sender == DAO, "Not DAO");
_;
}
// Stop flash attacks
modifier flashProof() {
require(isMature(), "No flash");
_;
}
function isMature() public view returns(bool){
return iUSDV(USDV).isMature();
}
//=====================================CREATION=========================================//
// Constructor
constructor() {
name = 'VADER PROTOCOL TOKEN';
symbol = 'VADER';
decimals = 18;
_1m = 10**6 * 10 ** decimals;
baseline = _1m;
totalSupply = 0;
maxSupply = 2 * _1m;
currentEra = 1;
secondsPerEra = 1;
nextEraTime = block.timestamp + secondsPerEra;
emissionCurve = 900;
DAO = msg.sender;
burnAddress = 0x0111011001100001011011000111010101100101;
}
// Can only be called once
function init(address _vether, address _USDV, address _utils) external {
require(inited == false);
inited = true;
VETHER = _vether;
USDV = _USDV;
UTILS = _utils;
rewardAddress = _USDV;
}
//========================================iERC20=========================================//
function balanceOf(address account) external view override returns (uint) {
return _balances[account];
}
function allowance(address owner, address spender) public view virtual override returns (uint) {
return _allowances[owner][spender];
}
// iERC20 Transfer function
function transfer(address recipient, uint amount) external virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
// iERC20 Approve, change allowance functions
function approve(address spender, uint amount) external virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function _approve(address owner, address spender, uint amount) internal virtual {
require(owner != address(0), "sender");
require(spender != address(0), "spender");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// iERC20 TransferFrom function
function transferFrom(address sender, address recipient, uint amount) external virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender] - amount);
return true;
}
// TransferTo function
// Risks: User can be phished, or tx.origin may be deprecated, optionality should exist in the system.
function transferTo(address recipient, uint amount) external virtual override returns (bool) {
_transfer(tx.origin, recipient, amount);
return true;
}
// Internal transfer function
function _transfer(address sender, address recipient, uint amount) internal virtual {
require(sender != address(0), "sender");
require(recipient != address(this), "recipient");
_balances[sender] -= amount;
uint _fee = iUTILS(UTILS).calcPart(feeOnTransfer, amount);
if(_fee >= 0 && _fee <= amount){
amount -= _fee;
_burn(msg.sender, _fee);
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_checkEmission();
}
// Internal mint (upgrading and daily emissions)
function _mint(address account, uint amount) internal virtual {
require(account != address(0), "recipient");
if((totalSupply + amount) >= maxSupply){
amount = maxSupply - totalSupply;
}
totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
// Burn supply
function burn(uint amount) public virtual override {
_burn(msg.sender, amount);
}
function burnFrom(address account, uint amount) external virtual override {
uint decreasedAllowance = allowance(account, msg.sender) - amount;
_approve(account, msg.sender, decreasedAllowance);
_burn(account, amount);
}
function _burn(address account, uint amount) internal virtual {
require(account != address(0), "address err");
_balances[account] -= amount;
totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
//=========================================DAO=========================================//
// Can start
function flipEmissions() external onlyDAO {
if(emitting){
emitting = false;
} else {
emitting = true;
}
}
// Can stop
function flipMinting() external onlyDAO {
if(minting){
minting = false;
} else {
minting = true;
}
}
// Can set params
function setParams(uint newEra, uint newCurve) external onlyDAO {
secondsPerEra = newEra;
emissionCurve = newCurve;
}
// Can set reward address
function setRewardAddress(address newAddress) external onlyDAO {
rewardAddress = newAddress;
}
// Can change UTILS
function changeUTILS(address newUTILS) external onlyDAO {
require(newUTILS != address(0), "address err");
UTILS = newUTILS;
}
// Can change DAO
function changeDAO(address newDAO) external onlyDAO {
require(newDAO != address(0), "address err");
DAO = newDAO;
}
// Can purge DAO
function purgeDAO() external onlyDAO{
DAO = address(0);
}
//======================================EMISSION========================================//
// Internal - Update emission function
function _checkEmission() private {
if ((block.timestamp >= nextEraTime) && emitting) {
currentEra += 1;
nextEraTime = block.timestamp + secondsPerEra;
uint _emission = getDailyEmission();
_mint(rewardAddress, _emission);
feeOnTransfer = iUTILS(UTILS).getFeeOnTransfer(totalSupply, maxSupply);
if(feeOnTransfer > 1000){feeOnTransfer = 1000;}
emit NewEra(currentEra, nextEraTime, _emission);
}
}
// Calculate Daily Emission
function getDailyEmission() public view returns (uint) {
uint _adjustedMax;
if(totalSupply <= baseline){
_adjustedMax = (maxSupply * totalSupply) / baseline;
} else {
_adjustedMax = maxSupply;
}
return (_adjustedMax - totalSupply) / (emissionCurve);
}
//======================================ASSET MINTING========================================//
// VETHER Owners to Upgrade
function upgrade(uint amount) external {
require(iERC20(VETHER).transferFrom(msg.sender, burnAddress, amount));
_mint(msg.sender, amount);
}
// Directly redeem back to VADER (must have sent USDV first)
function redeem() external returns (uint redeemAmount){
return redeemToMember(msg.sender);
}
// Redeem on behalf of member (must have sent USDV first)
function redeemToMember(address member) public flashProof returns (uint redeemAmount){
if(minting){
uint _amount = iERC20(USDV).balanceOf(address(this));
iERC20(USDV).burn(_amount);
redeemAmount = iROUTER(iUSDV(USDV).ROUTER()).getVADERAmount(_amount);
_mint(member, redeemAmount);
}
}
} | 1,960 | 245 | 3 | 1. [H-03] Missing DAO functionality to call changeDAO() function in Vader.sol. (Incorrect Functionality)
`changeDAO()` is authorized to be called only from the DAO (per modifier) but DAO contract has no corresponding functionality to call changeDAO() function. As a result, DAO address cannot be changed
2. [H-06] Incorrect burn address in Vader.sol. (tx.origin, access control)
The internal _transfer() function is called from external facing transfer(), transferFrom(), and transferTo() functions all of which have different sender addresses. It is msg.sender for transfer(), sender parameter for transferFrom() and `tx.origin` for transferTo().
3. [H-17] Transfer fee is burned on wrong accounts
The `Vader._transfer` function burns the transfer fee on msg.sender but this address might not be involved in the transfer at all due to transferFrom.
4. [H-25] Incorrect initialization causes VADER emission rate of 1 second instead of 1 day in Vader.sol
Incorrect initialization (perhaps testing parameterization mistakenly carried over to deployment) of `secondsPerEra` to 1 sec instead of 86400 secs (1 day) causes what should be the daily emission rate to be a secondly emission rate.
5. [M-13] Init function can be called by everyone. (Access control)
6. [M-15] changeDAO should be a two-step process in Vader.sol
changeDAO() updates DAO address in one-step. If an incorrect address is mistakenly used (and voted upon) then future administrative access or recovering from this mistake is prevented because onlyDAO modifier is used for changeDAO(), which requires msg.sender to be the incorrectly used DAO address (for which private keys may not be available to sign transactions).
7. [M-17] Vader.redeemToMember() vulnerable to front running (Front-running)
The USDV balance of the Vader contract is vulnerable to theft through the Vader.redeemToMember() function. A particular case is through USDV redemption front-running. Users can redeem USDV for Vader through the USDV.redeemForMember() function or the Vader.redeemToMember() function. | 7 |
16_GasOracle.sol | // SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../Interfaces/IOracle.sol";
import "../Interfaces/IChainlinkOracle.sol";
import "../lib/LibMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
/**
* @dev The following is a sample Gas Price Oracle Implementation for a Tracer Oracle.
* It references the Chainlink fast gas price and ETH/USD price to get a gas cost
* estimate in USD.
*/
contract GasOracle is IOracle, Ownable {
using LibMath for uint256;
IChainlinkOracle public gasOracle;
IChainlinkOracle public priceOracle;
uint8 public override decimals = 18;
uint256 private constant MAX_DECIMALS = 18;
constructor(address _priceOracle, address _gasOracle) {
gasOracle = IChainlinkOracle(_gasOracle);
priceOracle = IChainlinkOracle(_priceOracle);
}
/**
* @notice Calculates the latest USD/Gas price
* @dev Returned value is USD/Gas * 10^18 for compatibility with rest of calculations
*/
function latestAnswer() external view override returns (uint256) {
uint256 gasPrice = uint256(gasOracle.latestAnswer());
uint256 ethPrice = uint256(priceOracle.latestAnswer());
uint256 result = PRBMathUD60x18.mul(gasPrice, ethPrice);
return result;
}
/**
* @notice converts a raw value to a WAD value.
* @dev this allows consistency for oracles used throughout the protocol
* and allows oracles to have their decimals changed withou affecting
* the market itself
*/
function toWad(uint256 raw, IChainlinkOracle _oracle) internal view returns (uint256) {
IChainlinkOracle oracle = IChainlinkOracle(_oracle);
// reset the scaler for consistency
uint8 _decimals = oracle.decimals();
require(_decimals <= MAX_DECIMALS, "GAS: too many decimals");
uint256 scaler = uint256(10**(MAX_DECIMALS - _decimals));
return raw * scaler;
}
function setGasOracle(address _gasOracle) public onlyOwner {
require(_gasOracle != address(0), "address(0) given");
gasOracle = IChainlinkOracle(_gasOracle);
}
function setPriceOracle(address _priceOracle) public onlyOwner {
require(_priceOracle != address(0), "address(0) given");
priceOracle = IChainlinkOracle(_priceOracle);
}
function setDecimals(uint8 _decimals) external {
decimals = _decimals;
}
} | 603 | 68 | 0 | 1. [H-06] Wrong price scale for GasOracle (Price manipulation)
The GasOracle uses two chainlink oracles (GAS in ETH with some decimals, USD per ETH with some decimals) and multiplies their raw return values to get the gas price in USD.
| 1 |
23_NotionalV1ToNotionalV2.sol | // SPDX-License-Identifier: GPL-3.0-only
pragma solidity >0.7.0;
pragma experimental ABIEncoderV2;
import "../../global/Types.sol";
import "interfaces/notional/NotionalProxy.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface WETH9 {
function withdraw(uint256 wad) external;
function transfer(address dst, uint256 wad) external returns (bool);
}
interface IEscrow {
function getBalances(address account) external view returns (int256[] memory);
}
interface INotionalV1Erc1155 {
/** Notional V1 Types */
struct Deposit {
// Currency Id to deposit
uint16 currencyId;
// Amount of tokens to deposit
uint128 amount;
}
/**
* Used to describe withdraws in ERC1155.batchOperationWithdraw
*/
struct Withdraw {
// Destination of the address to withdraw to
address to;
// Currency Id to withdraw
uint16 currencyId;
// Amount of tokens to withdraw
uint128 amount;
}
enum TradeType {TakeCurrentCash, TakefCash, AddLiquidity, RemoveLiquidity}
/**
* Used to describe a trade in ERC1155.batchOperation
*/
struct Trade {
TradeType tradeType;
uint8 cashGroup;
uint32 maturity;
uint128 amount;
bytes slippageData;
}
function batchOperationWithdraw(
address account,
uint32 maxTime,
Deposit[] memory deposits,
Trade[] memory trades,
Withdraw[] memory withdraws
) external payable;
}
contract NotionalV1ToNotionalV2 {
IEscrow public immutable Escrow;
NotionalProxy public immutable NotionalV2;
INotionalV1Erc1155 public immutable NotionalV1Erc1155;
WETH9 public immutable WETH;
IERC20 public immutable WBTC;
uint16 internal constant V1_ETH = 0;
uint16 internal constant V1_DAI = 1;
uint16 internal constant V1_USDC = 2;
uint16 internal constant V1_WBTC = 3;
uint16 public constant V2_ETH = 1;
uint16 public immutable V2_DAI;
uint16 public immutable V2_USDC;
uint16 public immutable V2_WBTC;
constructor(
IEscrow escrow_,
NotionalProxy notionalV2_,
INotionalV1Erc1155 erc1155_,
WETH9 weth_,
IERC20 wbtc_,
uint16 v2Dai_,
uint16 v2USDC_,
uint16 v2WBTC_
) {
Escrow = escrow_;
NotionalV2 = notionalV2_;
NotionalV1Erc1155 = erc1155_;
WETH = weth_;
WBTC = wbtc_;
V2_DAI = v2Dai_;
V2_USDC = v2USDC_;
V2_WBTC = v2WBTC_;
}
function enableWBTC() external {
WBTC.approve(address(NotionalV2), type(uint256).max);
}
function migrateDaiEther(
uint128 v1RepayAmount,
BalanceActionWithTrades[] calldata borrowAction
) external {
// borrow on notional via special flash loan facility
// - borrow repayment amount
// - withdraw to wallet
// receive callback (tokens transferred to borrowing account)
// -> inside callback
// -> repay Notional V1
// -> deposit collateral to notional v2 (account needs to have set approvals)
// -> exit callback
// inside original borrow, check FC
bytes memory encodedData = abi.encode(V1_DAI, v1RepayAmount, V1_ETH, V2_ETH);
NotionalV2.batchBalanceAndTradeActionWithCallback(msg.sender, borrowAction, encodedData);
}
function migrateUSDCEther(
uint128 v1RepayAmount,
BalanceActionWithTrades[] calldata borrowAction
) external {
bytes memory encodedData = abi.encode(V1_USDC, v1RepayAmount, V1_ETH, V2_ETH);
NotionalV2.batchBalanceAndTradeActionWithCallback(msg.sender, borrowAction, encodedData);
}
function migrateDaiWBTC(
uint128 v1RepayAmount,
BalanceActionWithTrades[] calldata borrowAction
) external {
bytes memory encodedData = abi.encode(V1_DAI, v1RepayAmount, V1_WBTC, V2_WBTC);
NotionalV2.batchBalanceAndTradeActionWithCallback(msg.sender, borrowAction, encodedData);
}
function migrateUSDCWBTC(
uint128 v1RepayAmount,
BalanceActionWithTrades[] calldata borrowAction
) external {
bytes memory encodedData = abi.encode(V1_USDC, v1RepayAmount, V1_WBTC, V2_WBTC);
NotionalV2.batchBalanceAndTradeActionWithCallback(msg.sender, borrowAction, encodedData);
}
function notionalCallback(
address sender,
address account,
bytes calldata callbackData
) external returns (uint256) {
require(sender == address(this), "Unauthorized callback");
(
uint16 v1DebtCurrencyId,
uint128 v1RepayAmount,
uint16 v1CollateralId,
uint16 v2CollateralId
) = abi.decode(callbackData, (uint16, uint128, uint16, uint16));
int256[] memory balances = Escrow.getBalances(account);
int256 collateralBalance =
(v1CollateralId == V1_ETH ? balances[V1_ETH] : balances[V1_WBTC]);
require(collateralBalance > 0);
{
INotionalV1Erc1155.Deposit[] memory deposits = new INotionalV1Erc1155.Deposit[](1);
INotionalV1Erc1155.Trade[] memory trades = new INotionalV1Erc1155.Trade[](0);
INotionalV1Erc1155.Withdraw[] memory withdraws = new INotionalV1Erc1155.Withdraw[](1);
// This will deposit what was borrowed from the account's wallet
deposits[0].currencyId = v1DebtCurrencyId;
deposits[0].amount = v1RepayAmount;
// This will withdraw to the current contract the collateral to repay the flash loan
withdraws[0].currencyId = v1CollateralId;
withdraws[0].to = address(this);
withdraws[0].amount = uint128(collateralBalance);
NotionalV1Erc1155.batchOperationWithdraw(
account,
uint32(block.timestamp),
deposits,
trades,
withdraws
);
}
// Overflow checked above, cannot be negative
uint256 v2CollateralBalance = uint256(collateralBalance);
if (v2CollateralId == V2_ETH) {
// Notional V1 uses WETH, but V2 uses ETH
WETH.withdraw(v2CollateralBalance);
NotionalV2.depositUnderlyingToken{value: v2CollateralBalance}(
account,
v2CollateralId,
v2CollateralBalance
);
} else {
NotionalV2.depositUnderlyingToken(account, v2CollateralId, v2CollateralBalance);
}
// When this exits it will do a free collateral check
}
receive() external payable {}
} | 1,658 | 204 | 0 | 1. [H-05] Access restrictions on NotionalV1ToNotionalV2.notionalCallback can be bypassed (Centralized control)
The NotionalV1ToNotionalV2.notionalCallback is supposed to only be called from the verified contract that calls this callback but the access restrictions can be circumvented by simply providing `sender = this` as `sender` is a parameter of the function that can be chosen by the attacker.
| 1 |
14_BadgerYieldSource.sol | // SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import { IYieldSource } from "@pooltogether/yield-source-interface/contracts/IYieldSource.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IBadgerSett.sol";
import "./IBadger.sol";
import "hardhat/console.sol";
/// @title A pooltogether yield source for badger sett
/// @author Steffel Fenix, 0xkarl
contract BadgerYieldSource is IYieldSource {
using SafeMath for uint256;
IBadgerSett private immutable badgerSett;
IBadger private immutable badger;
mapping(address => uint256) private balances;
constructor(address badgerSettAddr, address badgerAddr) public {
badgerSett = IBadgerSett(badgerSettAddr);
badger = IBadger(badgerAddr);
}
/// @notice Returns the ERC20 asset token used for deposits.
/// @return The ERC20 asset token
function depositToken() public view override returns (address) {
return (address(badger));
}
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function balanceOfToken(address addr) public override returns (uint256) {
if (balances[addr] == 0) return 0;
uint256 totalShares = badgerSett.totalSupply();
uint256 badgerSettBadgerBalance = badger.balanceOf(address(badgerSett));
return (balances[addr].mul(badgerSettBadgerBalance).div(totalShares));
}
/// @notice Allows assets to be supplied on other user's behalf using the `to` param.
/// @param amount The amount of `token()` to be supplied
/// @param to The user whose balance will receive the tokens
function supplyTokenTo(uint256 amount, address to) public override {
badger.transferFrom(msg.sender, address(this), amount);
badger.approve(address(badgerSett), amount);
uint256 beforeBalance = badgerSett.balanceOf(address(this));
badgerSett.deposit(amount);
uint256 afterBalance = badgerSett.balanceOf(address(this));
uint256 balanceDiff = afterBalance.sub(beforeBalance);
balances[to] = balances[to].add(balanceDiff);
}
/// @notice Redeems tokens from the yield source to the msg.sender, it burns yield bearing tokens and returns token to the sender.
/// @param amount The amount of `token()` to withdraw. Denominated in `token()` as above.
/// @return The actual amount of tokens that were redeemed.
function redeemToken(uint256 amount) public override returns (uint256) {
uint256 totalShares = badgerSett.totalSupply();
if (totalShares == 0) return 0;
uint256 badgerSettBadgerBalance = badgerSett.balance();
if (badgerSettBadgerBalance == 0) return 0;
uint256 badgerBeforeBalance = badger.balanceOf(address(this));
uint256 requiredShares =
((amount.mul(totalShares) + totalShares)).div(
badgerSettBadgerBalance
);
if (requiredShares == 0) return 0;
uint256 requiredSharesBalance = requiredShares.sub(1);
badgerSett.withdraw(requiredSharesBalance);
uint256 badgerAfterBalance = badger.balanceOf(address(this));
uint256 badgerBalanceDiff = badgerAfterBalance.sub(badgerBeforeBalance);
balances[msg.sender] = balances[msg.sender].sub(requiredSharesBalance);
badger.transfer(msg.sender, badgerBalanceDiff);
return (badgerBalanceDiff);
}
} | 830 | 82 | 2 | 1. [H-03] BadgerYieldSource `balanceOfToken` share calculation seems wrong
The `balanceOfToken` function should then return the redeemable balance in badger for the user's badgerSett balance. It computes it as the pro-rata share of the user balance (compared to the total-supply of badgerSett) on the badger in the vault.
2. [M-02] Return values of ERC20 transfer and transferFrom are unchecked (Unchecked return values)
In the contracts BadgerYieldSource and SushiYieldSource, the return values of ERC20 `transfer` and `transferFrom` are not checked to be true, which could be false if the transferred tokens are not ERC20-compliant (e.g., BADGER). In that case, the transfer fails without being noticed by the calling contract.
3. [M-03] SafeMath not completely used in yield source contracts (Overflow)
`SafeMath` is not completely used at the following lines of yield source contracts, which could potentially cause arithmetic underflow and overflow: | 3 |
22_Staker.sol | // SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.3;
import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol";
import "./interfaces/IFloatToken.sol";
import "./interfaces/ILongShort.sol";
import "./interfaces/IStaker.sol";
import "./interfaces/ISyntheticToken.sol";
contract Staker is IStaker, Initializable {
/*╔═════════════════════════════╗
║ VARIABLES ║
╚═════════════════════════════╝*/
/* ══════ Fixed-precision constants ══════ */
uint256 public constant FLOAT_ISSUANCE_FIXED_DECIMAL = 1e42;
// 2^52 ~= 4.5e15
// With an exponent of 5, the largest total liquidity possible in a market (to avoid integer overflow on exponentiation) is ~10^31 or 10 Trillion (10^13)
// NOTE: this also means if the total market value is less than 2^52 there will be a division by zero error
uint256 public constant safeExponentBitShifting = 52;
/* ══════ Global state ══════ */
address public admin;
address public floatCapital;
address public floatTreasury;
uint256 public floatPercentage;
address public longShort;
address public floatToken;
/* ══════ Market specific ══════ */
mapping(uint32 => uint256) public marketLaunchIncentive_period;
// seconds
mapping(uint32 => uint256) public marketLaunchIncentive_multipliers;
// e18 scale
mapping(uint32 => uint256) public marketUnstakeFee_e18;
mapping(uint32 => uint256) public balanceIncentiveCurve_exponent;
mapping(uint32 => int256) public balanceIncentiveCurve_equilibriumOffset;
mapping(uint32 => mapping(bool => address)) public syntheticTokens;
mapping(address => uint32) public marketIndexOfToken;
/* ══════ Reward specific ══════ */
mapping(uint32 => uint256) public latestRewardIndex;
mapping(uint32 => mapping(uint256 => AccumulativeIssuancePerStakedSynthSnapshot))
public accumulativeFloatPerSyntheticTokenSnapshots;
struct AccumulativeIssuancePerStakedSynthSnapshot {
uint256 timestamp;
uint256 accumulativeFloatPerSyntheticToken_long;
uint256 accumulativeFloatPerSyntheticToken_short;
}
/* ══════ User specific ══════ */
mapping(uint32 => mapping(address => uint256)) public userIndexOfLastClaimedReward;
mapping(address => mapping(address => uint256)) public userAmountStaked;
/* ══════ Token shift management specific ══════ */
mapping(uint32 => uint256) public batched_stakerNextTokenShiftIndex;
/**
@notice Used to link a token shift to a staker state
@dev tokenShiftIndex => accumulativeFloatIssuanceSnapshotIndex
POSSIBLE OPTIMIZATION - could pack stakerTokenShiftIndex_to_accumulativeFloatIssuanceSnapshotIndex_mapping and stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mapping into a struct of two uint128 for storage space optimization.
*/
mapping(uint256 => uint256) public stakerTokenShiftIndex_to_accumulativeFloatIssuanceSnapshotIndex_mapping;
/// @notice Used to fetch the price from LongShort at that point in time
/// @dev tokenShiftIndex => longShortMarketPriceSnapshotIndex
mapping(uint256 => uint256) public stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mapping;
/// @dev marketIndex => usersAddress => stakerTokenShiftIndex
mapping(uint32 => mapping(address => uint256)) public userNextPrice_stakedSyntheticTokenShiftIndex;
/// @dev marketIndex => usersAddress => amountUserRequestedToShiftAwayFromLongOnNextUpdate
mapping(uint32 => mapping(address => uint256)) public userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long;
/// @dev marketIndex => usersAddress => amountUserRequestedToShiftAwayFromShortOnNextUpdate
mapping(uint32 => mapping(address => uint256)) public userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short;
/*╔════════════════════════════╗
║ EVENTS ║
╚════════════════════════════╝*/
event StakerV1(
address admin,
address floatTreasury,
address floatCapital,
address floatToken,
uint256 floatPercentage
);
event MarketAddedToStaker(
uint32 marketIndex,
uint256 exitFee_e18,
uint256 period,
uint256 multiplier,
uint256 balanceIncentiveExponent,
int256 balanceIncentiveEquilibriumOffset
);
event AccumulativeIssuancePerStakedSynthSnapshotCreated(
uint32 marketIndex,
uint256 accumulativeFloatIssuanceSnapshotIndex,
uint256 accumulativeLong,
uint256 accumulativeShort
);
event StakeAdded(address user, address token, uint256 amount, uint256 lastMintIndex);
event StakeWithdrawn(address user, address token, uint256 amount);
// Note: the `amountFloatMinted` isn't strictly needed by the graph, but it is good to add it to validate calculations are accurate.
event FloatMinted(address user, uint32 marketIndex, uint256 amountFloatMinted);
event MarketLaunchIncentiveParametersChanges(uint32 marketIndex, uint256 period, uint256 multiplier);
event StakeWithdrawalFeeUpdated(uint32 marketIndex, uint256 stakeWithdralFee);
event BalanceIncentiveExponentUpdated(uint32 marketIndex, uint256 balanceIncentiveExponent);
event BalanceIncentiveEquilibriumOffsetUpdated(uint32 marketIndex, int256 balanceIncentiveEquilibriumOffset);
event FloatPercentageUpdated(uint256 floatPercentage);
event SyntheticTokensShifted();
event ChangeAdmin(address newAdmin);
/*╔═════════════════════════════╗
║ MODIFIERS ║
╚═════════════════════════════╝*/
function onlyAdminModifierLogic() internal virtual {
require(msg.sender == admin, "not admin");
}
modifier onlyAdmin() {
onlyAdminModifierLogic();
_;
}
function onlyValidSyntheticModifierLogic(address _synth) internal virtual {
require(marketIndexOfToken[_synth] != 0, "not valid synth");
}
modifier onlyValidSynthetic(address _synth) {
onlyValidSyntheticModifierLogic(_synth);
_;
}
function onlyValidMarketModifierLogic(uint32 marketIndex) internal virtual {
require(address(syntheticTokens[marketIndex][true]) != address(0), "not valid market");
}
modifier onlyValidMarket(uint32 marketIndex) {
onlyValidMarketModifierLogic(marketIndex);
_;
}
function onlyLongShortModifierLogic() internal virtual {
require(msg.sender == address(longShort), "not long short");
}
modifier onlyLongShort() {
onlyLongShortModifierLogic();
_;
}
/*╔═════════════════════════════╗
║ CONTRACT SET-UP ║
╚═════════════════════════════╝*/
/**
@notice Initializes the contract.
@dev Calls OpenZeppelin's initializer modifier.
@param _admin Address of the admin role.
@param _longShort Address of the LongShort contract, a deployed LongShort.sol
@param _floatToken Address of the Float token earned by staking.
@param _floatTreasury Address of the treasury contract for managing fees.
@param _floatCapital Address of the contract which earns a fixed percentage of Float.
@param _floatPercentage Determines the float percentage that gets minted for Float Capital, base 1e18.
*/
function initialize(
address _admin,
address _longShort,
address _floatToken,
address _floatTreasury,
address _floatCapital,
uint256 _floatPercentage
) external virtual initializer {
admin = _admin;
floatCapital = _floatCapital;
floatTreasury = _floatTreasury;
longShort = _longShort;
floatToken = _floatToken;
_changeFloatPercentage(_floatPercentage);
emit StakerV1(_admin, _floatTreasury, _floatCapital, _floatToken, _floatPercentage);
}
/*╔═══════════════════╗
║ ADMIN ║
╚═══════════════════╝*/
/**
@notice Changes admin for the contract
@param _admin The address of the new admin.
*/
function changeAdmin(address _admin) external onlyAdmin {
admin = _admin;
emit ChangeAdmin(_admin);
}
/// @dev Logic for changeFloatPercentage
function _changeFloatPercentage(uint256 newFloatPercentage) internal virtual {
require(newFloatPercentage <= 1e18 && newFloatPercentage > 0);
// less than or equal to 100% and greater than 0%
floatPercentage = newFloatPercentage;
}
/**
@notice Changes percentage of float that is minted for float capital.
@param newFloatPercentage The new float percentage in base 1e18.
*/
function changeFloatPercentage(uint256 newFloatPercentage) external onlyAdmin {
_changeFloatPercentage(newFloatPercentage);
emit FloatPercentageUpdated(newFloatPercentage);
}
/// @dev Logic for changeUnstakeFee
function _changeUnstakeFee(uint32 marketIndex, uint256 newMarketUnstakeFee_e18) internal virtual {
require(newMarketUnstakeFee_e18 <= 5e16);
// Explicitely stating 5% fee as the max fee possible.
marketUnstakeFee_e18[marketIndex] = newMarketUnstakeFee_e18;
}
/**
@notice Changes unstake fee for a market
@param marketIndex Identifies the market.
@param newMarketUnstakeFee_e18 The new unstake fee.
*/
function changeUnstakeFee(uint32 marketIndex, uint256 newMarketUnstakeFee_e18) external onlyAdmin {
_changeUnstakeFee(marketIndex, newMarketUnstakeFee_e18);
emit StakeWithdrawalFeeUpdated(marketIndex, newMarketUnstakeFee_e18);
}
/// @dev Logic for changeMarketLaunchIncentiveParameters
function _changeMarketLaunchIncentiveParameters(
uint32 marketIndex,
uint256 period,
uint256 initialMultiplier
) internal virtual {
require(initialMultiplier >= 1e18, "marketLaunchIncentiveMultiplier must be >= 1e18");
marketLaunchIncentive_period[marketIndex] = period;
marketLaunchIncentive_multipliers[marketIndex] = initialMultiplier;
}
/**
@notice Changes the market launch incentive parameters for a market
@param marketIndex Identifies the market.
@param period The new period for which float token generation should be boosted.
@param initialMultiplier The new multiplier on Float generation.
*/
function changeMarketLaunchIncentiveParameters(
uint32 marketIndex,
uint256 period,
uint256 initialMultiplier
) external onlyAdmin {
_changeMarketLaunchIncentiveParameters(marketIndex, period, initialMultiplier);
emit MarketLaunchIncentiveParametersChanges(marketIndex, period, initialMultiplier);
}
/// @dev Logic for changeBalanceIncentiveExponent
function _changeBalanceIncentiveExponent(uint32 marketIndex, uint256 _balanceIncentiveCurve_exponent)
internal
virtual
{
require(
// The exponent has to be less than 5 in these versions of the contracts.
_balanceIncentiveCurve_exponent > 0 && _balanceIncentiveCurve_exponent < 6,
"balanceIncentiveCurve_exponent out of bounds"
);
balanceIncentiveCurve_exponent[marketIndex] = _balanceIncentiveCurve_exponent;
}
/**
@notice Changes the balance incentive exponent for a market
@param marketIndex Identifies the market.
@param _balanceIncentiveCurve_exponent The new exponent for the curve.
*/
function changeBalanceIncentiveExponent(uint32 marketIndex, uint256 _balanceIncentiveCurve_exponent)
external
onlyAdmin
{
_changeBalanceIncentiveExponent(marketIndex, _balanceIncentiveCurve_exponent);
emit BalanceIncentiveExponentUpdated(marketIndex, _balanceIncentiveCurve_exponent);
}
/// @dev Logic for changeBalanceIncentiveEquilibriumOffset
function _changeBalanceIncentiveEquilibriumOffset(uint32 marketIndex, int256 _balanceIncentiveCurve_equilibriumOffset)
internal
virtual
{
// Unreasonable that we would ever shift this more than 90% either way
require(
_balanceIncentiveCurve_equilibriumOffset > -9e17 && _balanceIncentiveCurve_equilibriumOffset < 9e17,
"balanceIncentiveCurve_equilibriumOffset out of bounds"
);
balanceIncentiveCurve_equilibriumOffset[marketIndex] = _balanceIncentiveCurve_equilibriumOffset;
}
/**
@notice Changes the balance incentive curve equilibrium offset for a market
@param marketIndex Identifies the market.
@param _balanceIncentiveCurve_equilibriumOffset The new offset.
*/
function changeBalanceIncentiveEquilibriumOffset(uint32 marketIndex, int256 _balanceIncentiveCurve_equilibriumOffset)
external
onlyAdmin
{
_changeBalanceIncentiveEquilibriumOffset(marketIndex, _balanceIncentiveCurve_equilibriumOffset);
emit BalanceIncentiveEquilibriumOffsetUpdated(marketIndex, _balanceIncentiveCurve_equilibriumOffset);
}
/*╔═════════════════════════════╗
║ STAKING SETUP ║
╚═════════════════════════════╝*/
/**
@notice Sets this contract to track staking for a market in LongShort.sol
@param marketIndex Identifies the market.
@param longToken Address of the long token for the market.
@param shortToken Address of the short token for the market.
@param kInitialMultiplier Initial boost on float generation for the market.
@param kPeriod Period which the boost should last.
@param unstakeFee_e18 Percentage of tokens that are levied on unstaking in base 1e18.
@param _balanceIncentiveCurve_exponent Exponent for balance curve (see _calculateFloatPerSecond)
@param _balanceIncentiveCurve_equilibriumOffset Offset for balance curve (see _calculateFloatPerSecond)
*/
function addNewStakingFund(
uint32 marketIndex,
address longToken,
address shortToken,
uint256 kInitialMultiplier,
uint256 kPeriod,
uint256 unstakeFee_e18,
uint256 _balanceIncentiveCurve_exponent,
int256 _balanceIncentiveCurve_equilibriumOffset
) external override onlyLongShort {
marketIndexOfToken[longToken] = marketIndex;
marketIndexOfToken[shortToken] = marketIndex;
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][0].timestamp = block.timestamp;
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][0].accumulativeFloatPerSyntheticToken_long = 0;
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][0].accumulativeFloatPerSyntheticToken_short = 0;
syntheticTokens[marketIndex][true] = longToken;
syntheticTokens[marketIndex][false] = shortToken;
_changeBalanceIncentiveExponent(marketIndex, _balanceIncentiveCurve_exponent);
_changeBalanceIncentiveEquilibriumOffset(marketIndex, _balanceIncentiveCurve_equilibriumOffset);
_changeMarketLaunchIncentiveParameters(marketIndex, kPeriod, kInitialMultiplier);
_changeUnstakeFee(marketIndex, unstakeFee_e18);
// Set this value to one initially - 0 is a null value and thus potentially bug prone.
batched_stakerNextTokenShiftIndex[marketIndex] = 1;
emit MarketAddedToStaker(
marketIndex,
unstakeFee_e18,
kPeriod,
kInitialMultiplier,
_balanceIncentiveCurve_exponent,
_balanceIncentiveCurve_equilibriumOffset
);
emit AccumulativeIssuancePerStakedSynthSnapshotCreated(marketIndex, 0, 0, 0);
}
/*╔═════════════════════════════════════════════════════════════════════════╗
║ GLOBAL FLT REWARD ACCUMULATION CALCULATION AND TRACKING FUNCTIONS ║
╚═════════════════════════════════════════════════════════════════════════╝*/
/**
@notice Returns the K factor parameters for the given market with sensible
defaults if they haven't been set yet.
@param marketIndex The market to change the parameters for.
@return period The period for which the k factor applies for in seconds.
@return multiplier The multiplier on Float generation in this period.
*/
function _getMarketLaunchIncentiveParameters(uint32 marketIndex)
internal
view
virtual
returns (uint256 period, uint256 multiplier)
{
period = marketLaunchIncentive_period[marketIndex];
multiplier = marketLaunchIncentive_multipliers[marketIndex];
if (multiplier < 1e18) {
multiplier = 1e18;
// multiplier of 1 by default
}
}
/**
@notice Returns the extent to which a markets float generation should be adjusted
based on the market's launch incentive parameters. Should start at multiplier
then linearly change to 1e18 over time.
@param marketIndex Identifies the market.
@return k The calculated modifier for float generation.
*/
function _getKValue(uint32 marketIndex) internal view virtual returns (uint256) {
// Parameters controlling the float issuance multiplier.
(uint256 kPeriod, uint256 kInitialMultiplier) = _getMarketLaunchIncentiveParameters(marketIndex);
// Sanity check - under normal circumstances, the multipliers should
// *never* be set to a value < 1e18, as there are guards against this.
assert(kInitialMultiplier >= 1e18);
uint256 initialTimestamp = accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][0].timestamp;
if (block.timestamp - initialTimestamp <= kPeriod) {
return kInitialMultiplier - (((kInitialMultiplier - 1e18) * (block.timestamp - initialTimestamp)) / kPeriod);
} else {
return 1e18;
}
}
/*
@notice Computes the number of float tokens a user earns per second for
every long/short synthetic token they've staked. The returned value has
a fixed decimal scale of 1e42 (!!!) for numerical stability. The return
values are float per second per synthetic token (hence the requirement
to multiply by price)
@dev to see below math in latex form see TODO add link
to interact with the equations see https://www.desmos.com/calculator/optkaxyihr
@param marketIndex The market referred to.
@param longPrice Price of the synthetic long token in units of payment token
@param shortPrice Price of the synthetic short token in units of payment token
@param longValue Amount of payment token in the long side of the market
@param shortValue Amount of payment token in the short side of the market
@return longFloatPerSecond Float token per second per long synthetic token
@return shortFloatPerSecond Float token per second per short synthetic token
*/
function _calculateFloatPerSecond(
uint32 marketIndex,
uint256 longPrice,
uint256 shortPrice,
uint256 longValue,
uint256 shortValue
) internal view virtual returns (uint256 longFloatPerSecond, uint256 shortFloatPerSecond) {
// A float issuance multiplier that starts high and decreases linearly
// over time to a value of 1. This incentivises users to stake early.
uint256 k = _getKValue(marketIndex);
uint256 totalLocked = (longValue + shortValue);
// we need to scale this number by the totalLocked so that the offset remains consistent accross market size
int256 equilibriumOffsetMarketScaled = (balanceIncentiveCurve_equilibriumOffset[marketIndex] *
int256(totalLocked)) / 2e18;
uint256 denominator = ((totalLocked >> safeExponentBitShifting)**balanceIncentiveCurve_exponent[marketIndex]);
// Float is scaled by the percentage of the total market value held in
// the opposite position. This incentivises users to stake on the
// weaker position.
if (int256(shortValue) - equilibriumOffsetMarketScaled < int256(longValue)) {
if (equilibriumOffsetMarketScaled >= int256(shortValue)) {
// edge case: imbalanced far past the equilibrium offset - full rewards go to short token
// extremeley unlikely to happen in practice
return (0, 1e18 * k * shortPrice);
}
uint256 numerator = (uint256(int256(shortValue) - equilibriumOffsetMarketScaled) >>
(safeExponentBitShifting - 1))**balanceIncentiveCurve_exponent[marketIndex];
// NOTE: `x * 5e17` == `(x * 10e18) / 2`
uint256 longRewardUnscaled = (numerator * 5e17) / denominator;
uint256 shortRewardUnscaled = 1e18 - longRewardUnscaled;
return ((longRewardUnscaled * k * longPrice) / 1e18, (shortRewardUnscaled * k * shortPrice) / 1e18);
} else {
if (-equilibriumOffsetMarketScaled >= int256(longValue)) {
// edge case: imbalanced far past the equilibrium offset - full rewards go to long token
// extremeley unlikely to happen in practice
return (1e18 * k * longPrice, 0);
}
uint256 numerator = (uint256(int256(longValue) + equilibriumOffsetMarketScaled) >>
(safeExponentBitShifting - 1))**balanceIncentiveCurve_exponent[marketIndex];
// NOTE: `x * 5e17` == `(x * 10e18) / 2`
uint256 shortRewardUnscaled = (numerator * 5e17) / denominator;
uint256 longRewardUnscaled = 1e18 - shortRewardUnscaled;
return ((longRewardUnscaled * k * longPrice) / 1e18, (shortRewardUnscaled * k * shortPrice) / 1e18);
}
}
/**
@notice Computes the time since last accumulativeIssuancePerStakedSynthSnapshot for the given market in seconds.
@param marketIndex The market referred to.
@return The time difference in seconds
*/
function _calculateTimeDeltaFromLastAccumulativeIssuancePerStakedSynthSnapshot(uint32 marketIndex)
internal
view
virtual
returns (uint256)
{
return
block.timestamp -
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][latestRewardIndex[marketIndex]].timestamp;
}
/**
@notice Computes new cumulative sum of 'r' value since last accumulativeIssuancePerStakedSynthSnapshot. We use
cumulative 'r' value to avoid looping during issuance. Note that the
cumulative sum is kept in 1e42 scale (!!!) to avoid numerical issues.
@param shortValue The value locked in the short side of the market.
@param longValue The value locked in the long side of the market.
@param shortPrice The price of the short token as defined in LongShort.sol
@param longPrice The price of the long token as defined in LongShort.sol
@param marketIndex An identifier for the market.
@return longCumulativeRates The long cumulative sum.
@return shortCumulativeRates The short cumulative sum.
*/
function _calculateNewCumulativeIssuancePerStakedSynth(
uint32 marketIndex,
uint256 longPrice,
uint256 shortPrice,
uint256 longValue,
uint256 shortValue
) internal view virtual returns (uint256 longCumulativeRates, uint256 shortCumulativeRates) {
// Compute the current 'r' value for float issuance per second.
(uint256 longFloatPerSecond, uint256 shortFloatPerSecond) = _calculateFloatPerSecond(
marketIndex,
longPrice,
shortPrice,
longValue,
shortValue
);
// Compute time since last accumulativeIssuancePerStakedSynthSnapshot for the given token.
uint256 timeDelta = _calculateTimeDeltaFromLastAccumulativeIssuancePerStakedSynthSnapshot(marketIndex);
// Compute new cumulative 'r' value total.
return (
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][latestRewardIndex[marketIndex]]
.accumulativeFloatPerSyntheticToken_long + (timeDelta * longFloatPerSecond),
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][latestRewardIndex[marketIndex]]
.accumulativeFloatPerSyntheticToken_short + (timeDelta * shortFloatPerSecond)
);
}
/**
@notice Creates a new accumulativeIssuancePerStakedSynthSnapshot for the given token and updates indexes.
@param shortValue The value locked in the short side of the market.
@param longValue The value locked in the long side of the market.
@param shortPrice The price of the short token as defined in LongShort.sol
@param longPrice The price of the long token as defined in LongShort.sol
@param marketIndex An identifier for the market.
*/
function _setCurrentAccumulativeIssuancePerStakeStakedSynthSnapshot(
uint32 marketIndex,
uint256 longPrice,
uint256 shortPrice,
uint256 longValue,
uint256 shortValue
) internal virtual {
(
uint256 newLongAccumulativeValue,
uint256 newShortAccumulativeValue
) = _calculateNewCumulativeIssuancePerStakedSynth(marketIndex, longPrice, shortPrice, longValue, shortValue);
uint256 newIndex = latestRewardIndex[marketIndex] + 1;
// Set cumulative 'r' value on new accumulativeIssuancePerStakedSynthSnapshot.
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][newIndex]
.accumulativeFloatPerSyntheticToken_long = newLongAccumulativeValue;
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][newIndex]
.accumulativeFloatPerSyntheticToken_short = newShortAccumulativeValue;
// Set timestamp on new accumulativeIssuancePerStakedSynthSnapshot.
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][newIndex].timestamp = block.timestamp;
// Update latest index to point to new accumulativeIssuancePerStakedSynthSnapshot.
latestRewardIndex[marketIndex] = newIndex;
emit AccumulativeIssuancePerStakedSynthSnapshotCreated(
marketIndex,
newIndex,
newLongAccumulativeValue,
newShortAccumulativeValue
);
}
/**
@notice Adds new accumulativeIssuancePerStakedSynthSnapshots for the given long/short tokens. Called by the
ILongShort contract whenever there is a state change for a market.
@param stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mappingIfShiftExecuted Mapping from this contract's shifts to LongShort.sols next price snapshots.
@param shortValue The value locked in the short side of the market.
@param longValue The value locked in the long side of the market.
@param shortPrice The price of the short token as defined in LongShort.sol
@param longPrice The price of the long token as defined in LongShort.sol
@param marketIndex An identifier for the market.
*/
function pushUpdatedMarketPricesToUpdateFloatIssuanceCalculations(
uint32 marketIndex,
uint256 longPrice,
uint256 shortPrice,
uint256 longValue,
uint256 shortValue,
uint256 stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mappingIfShiftExecuted // This value should be ALWAYS be zero if no shift occured
) external override onlyLongShort {
// Only add a new accumulativeIssuancePerStakedSynthSnapshot if some time has passed.
// the `stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mappingIfShiftExecuted` value will be 0 if there is no staker related action in an executed batch
if (stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mappingIfShiftExecuted > 0) {
stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mapping[
batched_stakerNextTokenShiftIndex[marketIndex]
] = stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mappingIfShiftExecuted;
stakerTokenShiftIndex_to_accumulativeFloatIssuanceSnapshotIndex_mapping[
batched_stakerNextTokenShiftIndex[marketIndex]
] = latestRewardIndex[marketIndex] + 1;
batched_stakerNextTokenShiftIndex[marketIndex] += 1;
emit SyntheticTokensShifted();
}
// Time delta is fetched twice in below code, can pass through? Which is less gas?
if (_calculateTimeDeltaFromLastAccumulativeIssuancePerStakedSynthSnapshot(marketIndex) > 0) {
_setCurrentAccumulativeIssuancePerStakeStakedSynthSnapshot(
marketIndex,
longPrice,
shortPrice,
longValue,
shortValue
);
}
}
/*╔═══════════════════════════════════╗
║ USER REWARD STATE FUNCTIONS ║
╚═══════════════════════════════════╝*/
/// @dev Calculates the accumulated float in a specific range of staker snapshots
function _calculateAccumulatedFloatInRange(
uint32 marketIndex,
uint256 amountStakedLong,
uint256 amountStakedShort,
uint256 rewardIndexFrom,
uint256 rewardIndexTo
) internal view virtual returns (uint256 floatReward) {
if (amountStakedLong > 0) {
uint256 accumDeltaLong = accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][rewardIndexTo]
.accumulativeFloatPerSyntheticToken_long -
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][rewardIndexFrom]
.accumulativeFloatPerSyntheticToken_long;
floatReward += (accumDeltaLong * amountStakedLong) / FLOAT_ISSUANCE_FIXED_DECIMAL;
}
if (amountStakedShort > 0) {
uint256 accumDeltaShort = accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][rewardIndexTo]
.accumulativeFloatPerSyntheticToken_short -
accumulativeFloatPerSyntheticTokenSnapshots[marketIndex][rewardIndexFrom]
.accumulativeFloatPerSyntheticToken_short;
floatReward += (accumDeltaShort * amountStakedShort) / FLOAT_ISSUANCE_FIXED_DECIMAL;
}
}
/**
@notice Calculates float owed to the user since the user last minted float for a market.
@param marketIndex Identifier for the market which the user staked in.
@param user The address of the user.
@return floatReward The amount of float owed.
*/
function _calculateAccumulatedFloat(uint32 marketIndex, address user) internal virtual returns (uint256 floatReward) {
address longToken = syntheticTokens[marketIndex][true];
address shortToken = syntheticTokens[marketIndex][false];
uint256 amountStakedLong = userAmountStaked[longToken][user];
uint256 amountStakedShort = userAmountStaked[shortToken][user];
uint256 usersLastRewardIndex = userIndexOfLastClaimedReward[marketIndex][user];
// Don't do the calculation and return zero immediately if there is no change
if (usersLastRewardIndex == latestRewardIndex[marketIndex]) {
return 0;
}
uint256 usersShiftIndex = userNextPrice_stakedSyntheticTokenShiftIndex[marketIndex][user];
// if there is a change in the users tokens held due to a token shift (or possibly another action in the future)
if (usersShiftIndex > 0 && usersShiftIndex < batched_stakerNextTokenShiftIndex[marketIndex]) {
floatReward = _calculateAccumulatedFloatInRange(
marketIndex,
amountStakedLong,
amountStakedShort,
usersLastRewardIndex,
stakerTokenShiftIndex_to_accumulativeFloatIssuanceSnapshotIndex_mapping[usersShiftIndex]
);
// Update the users balances
if (userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long[marketIndex][user] > 0) {
amountStakedShort += ILongShort(longShort).getAmountSyntheticTokenToMintOnTargetSide(
marketIndex,
userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long[marketIndex][user],
true,
stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mapping[usersShiftIndex]
);
amountStakedLong -= userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long[marketIndex][user];
userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long[marketIndex][user] = 0;
}
if (userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short[marketIndex][user] > 0) {
amountStakedLong += ILongShort(longShort).getAmountSyntheticTokenToMintOnTargetSide(
marketIndex,
userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short[marketIndex][user],
false,
stakerTokenShiftIndex_to_longShortMarketPriceSnapshotIndex_mapping[usersShiftIndex]
);
amountStakedShort -= userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short[marketIndex][user];
userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short[marketIndex][user] = 0;
}
// Save the users updated staked amounts
userAmountStaked[longToken][user] = amountStakedLong;
userAmountStaked[shortToken][user] = amountStakedShort;
floatReward += _calculateAccumulatedFloatInRange(
marketIndex,
amountStakedLong,
amountStakedShort,
stakerTokenShiftIndex_to_accumulativeFloatIssuanceSnapshotIndex_mapping[usersShiftIndex],
latestRewardIndex[marketIndex]
);
userNextPrice_stakedSyntheticTokenShiftIndex[marketIndex][user] = 0;
} else {
floatReward = _calculateAccumulatedFloatInRange(
marketIndex,
amountStakedLong,
amountStakedShort,
usersLastRewardIndex,
latestRewardIndex[marketIndex]
);
}
}
/**
@notice Mints float for a user.
@dev Mints a fixed percentage for Float capital.
@param user The address of the user.
@param floatToMint The amount of float to mint.
*/
function _mintFloat(address user, uint256 floatToMint) internal virtual {
IFloatToken(floatToken).mint(user, floatToMint);
IFloatToken(floatToken).mint(floatCapital, (floatToMint * floatPercentage) / 1e18);
}
/**
@notice Mints float owed to a user for a market since they last minted.
@param marketIndex An identifier for the market.
@param user The address of the user.
*/
function _mintAccumulatedFloat(uint32 marketIndex, address user) internal virtual {
uint256 floatToMint = _calculateAccumulatedFloat(marketIndex, user);
if (floatToMint > 0) {
// Set the user has claimed up until now, stops them setting this forward
userIndexOfLastClaimedReward[marketIndex][user] = latestRewardIndex[marketIndex];
_mintFloat(user, floatToMint);
emit FloatMinted(user, marketIndex, floatToMint);
}
}
/**
@notice Mints float owed to a user for multiple markets, since they last minted for those markets.
@param marketIndexes Identifiers for the markets.
@param user The address of the user.
*/
function _mintAccumulatedFloatMulti(uint32[] calldata marketIndexes, address user) internal virtual {
uint256 floatTotal = 0;
for (uint256 i = 0; i < marketIndexes.length; i++) {
uint256 floatToMint = _calculateAccumulatedFloat(marketIndexes[i], user);
if (floatToMint > 0) {
// Set the user has claimed up until now, stops them setting this forward
userIndexOfLastClaimedReward[marketIndexes[i]][user] = latestRewardIndex[marketIndexes[i]];
floatTotal += floatToMint;
emit FloatMinted(user, marketIndexes[i], floatToMint);
}
}
if (floatTotal > 0) {
_mintFloat(user, floatTotal);
}
}
/**
@notice Mints outstanding float for msg.sender.
@param marketIndexes Identifiers for the markets for which to mint float.
*/
function claimFloatCustom(uint32[] calldata marketIndexes) external {
ILongShort(longShort).updateSystemStateMulti(marketIndexes);
_mintAccumulatedFloatMulti(marketIndexes, msg.sender);
}
/**
@notice Mints outstanding float on behalf of another user.
@param marketIndexes Identifiers for the markets for which to mint float.
@param user The address of the user.
*/
function claimFloatCustomFor(uint32[] calldata marketIndexes, address user) external {
// Unbounded loop - users are responsible for paying their own gas costs on these and it doesn't effect the rest of the system.
// No need to impose limit.
ILongShort(longShort).updateSystemStateMulti(marketIndexes);
_mintAccumulatedFloatMulti(marketIndexes, user);
}
/*╔═══════════════════════╗
║ STAKING ║
╚═══════════════════════╝*/
/**
@notice A user with synthetic tokens stakes by calling stake on the token
contract which calls this function. We need to first update the
state of the LongShort contract for this market before staking to correctly calculate user rewards.
@param amount Amount to stake.
@param from Address to stake for.
*/
function stakeFromUser(address from, uint256 amount) public virtual override onlyValidSynthetic((msg.sender)) {
ILongShort(longShort).updateSystemState(marketIndexOfToken[(msg.sender)]);
_stake((msg.sender), amount, from);
}
/**
@dev Internal logic for staking.
@param token Address of the token for which to stake.
@param amount Amount to stake.
@param user Address to stake for.
*/
function _stake(
address token,
uint256 amount,
address user
) internal virtual {
uint32 marketIndex = marketIndexOfToken[token];
// If they already have staked and have rewards due, mint these.
if (
userIndexOfLastClaimedReward[marketIndex][user] != 0 &&
userIndexOfLastClaimedReward[marketIndex][user] < latestRewardIndex[marketIndex]
) {
_mintAccumulatedFloat(marketIndex, user);
}
userAmountStaked[token][user] = userAmountStaked[token][user] + amount;
userIndexOfLastClaimedReward[marketIndex][user] = latestRewardIndex[marketIndex];
emit StakeAdded(user, address(token), amount, userIndexOfLastClaimedReward[marketIndex][user]);
}
/**
@notice Allows users to shift their staked tokens from one side of the market to
the other at the next price.
@param amountSyntheticTokensToShift Amount of tokens to shift.
@param marketIndex Identifier for the market.
@param isShiftFromLong Whether the shift is from long to short or short to long.
*/
function shiftTokens(
uint256 amountSyntheticTokensToShift,
uint32 marketIndex,
bool isShiftFromLong
) external virtual {
address token = syntheticTokens[marketIndex][isShiftFromLong];
require(userAmountStaked[token][msg.sender] >= amountSyntheticTokensToShift, "Not enough tokens to shift");
// If the user has outstanding token shift that have already been confirmed in the LongShort
// contract, execute them first.
if (
userNextPrice_stakedSyntheticTokenShiftIndex[marketIndex][msg.sender] != 0 &&
userNextPrice_stakedSyntheticTokenShiftIndex[marketIndex][msg.sender] <
batched_stakerNextTokenShiftIndex[marketIndex]
) {
_mintAccumulatedFloat(marketIndex, msg.sender);
}
if (isShiftFromLong) {
ILongShort(longShort).shiftPositionFromLongNextPrice(marketIndex, amountSyntheticTokensToShift);
userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long[marketIndex][
msg.sender
] += amountSyntheticTokensToShift;
} else {
ILongShort(longShort).shiftPositionFromShortNextPrice(marketIndex, amountSyntheticTokensToShift);
userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short[marketIndex][
msg.sender
] += amountSyntheticTokensToShift;
}
userNextPrice_stakedSyntheticTokenShiftIndex[marketIndex][msg.sender] = batched_stakerNextTokenShiftIndex[
marketIndex
];
}
/*╔════════════════════════════╗
║ WITHDRAWAL & MINTING ║
╚════════════════════════════╝*/
/**
@notice Internal logic for withdrawing stakes.
@dev Mint user any outstanding float before withdrawing.
@param marketIndex Market index of token.
@param amount Amount to withdraw.
@param token Synthetic token that was staked.
*/
function _withdraw(
uint32 marketIndex,
address token,
uint256 amount
) internal virtual {
require(userAmountStaked[token][msg.sender] > 0, "nothing to withdraw");
_mintAccumulatedFloat(marketIndex, msg.sender);
userAmountStaked[token][msg.sender] = userAmountStaked[token][msg.sender] - amount;
uint256 amountFees = (amount * marketUnstakeFee_e18[marketIndex]) / 1e18;
IERC20(token).transfer(floatTreasury, amountFees);
IERC20(token).transfer(msg.sender, amount - amountFees);
emit StakeWithdrawn(msg.sender, token, amount);
}
/**
@notice Withdraw function. Allows users to unstake.
@param amount Amount to withdraw.
@param token Address of the token for which to withdraw.
*/
function withdraw(address token, uint256 amount) external {
ILongShort(longShort).updateSystemState(marketIndexOfToken[token]);
uint32 marketIndex = marketIndexOfToken[token];
_withdraw(marketIndex, token, amount);
if (userNextPrice_stakedSyntheticTokenShiftIndex[marketIndex][msg.sender] > 0) {
// If they still have outstanding shifts after minting float, then check
// that they don't withdraw more than their shifts allow.
uint256 amountToShiftForThisToken = syntheticTokens[marketIndex][true] == token
? userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long[marketIndex][msg.sender]
: userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short[marketIndex][msg.sender];
require(
userAmountStaked[token][msg.sender] >= amountToShiftForThisToken,
"Outstanding next price stake shifts too great"
);
}
}
/**
@notice Allows users to withdraw their entire stake for a token.
@param token Address of the token for which to withdraw.
*/
function withdrawAll(address token) external {
ILongShort(longShort).updateSystemState(marketIndexOfToken[token]);
uint32 marketIndex = marketIndexOfToken[token];
uint256 amountToShiftForThisToken = syntheticTokens[marketIndex][true] == token
? userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_long[marketIndex][msg.sender]
: userNextPrice_amountStakedSyntheticToken_toShiftAwayFrom_short[marketIndex][msg.sender];
_withdraw(marketIndex, token, userAmountStaked[token][msg.sender] - amountToShiftForThisToken);
}
} | 10,105 | 990 | 0 | 1. [H-02] 2 variables not indexed by marketIndex. L622
in function `pushUpdatedMarketPricesToUpdateFloatIssuanceCalculations()`
2. [H-03] Users could shift tokens on Staker with more than he has staked. (Lack of input validation)
The `shiftTokens` function of Staker checks whether the user has staked at least the number of tokens he wants to shift from one side to the other (line 885).
3. [M-04] Staker.sol: Wrong values returned in edge cases of `_calculateFloatPerSecond()` (Lack of input validation) | 3 |
8_ERC20FlashMintUpgradeable.sol | // SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
import "../interface/IERC3156Upgradeable.sol";
import "./ERC20Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the ERC3156 Flash loans extension, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* Adds the {flashLoan} method, which provides flash loan support at the token
* level. By default there is no fee, but this can be changed by overriding {flashFee}.
*/
abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable {
function __ERC20FlashMint_init() internal initializer {
__Context_init_unchained();
__ERC20FlashMint_init_unchained();
}
function __ERC20FlashMint_init_unchained() internal initializer {
}
bytes32 constant private RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
/**
* @dev Returns the maximum amount of tokens available for loan.
* @param token The address of the token that is requested.
* @return The amont of token that can be loaned.
*/
function maxFlashLoan(address token) public view override returns (uint256) {
return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0;
}
/**
* @dev Returns the fee applied when doing flash loans. By default this
* implementation has 0 fees. This function can be overloaded to make
* the flash loan mechanism deflationary.
* @param token The token to be flash loaned.
* @param amount The amount of tokens to be loaned.
* @return The fees applied to the corresponding flash loan.
*/
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) {
require(token == address(this), "ERC20FlashMint: wrong token");
// silence warning about unused variable without the addition of bytecode.
amount;
return 0;
}
/**
* @dev Performs a flash loan. New tokens are minted and sent to the
* `receiver`, who is required to implement the {IERC3156FlashBorrower}
* interface. By the end of the flash loan, the receiver is expected to own
* amount + fee tokens and have them approved back to the token contract itself so
* they can be burned.
* @param receiver The receiver of the flash loan. Should implement the
* {IERC3156FlashBorrower.onFlashLoan} interface.
* @param token The token to be flash loaned. Only `address(this)` is
* supported.
* @param amount The amount of tokens to be loaned.
* @param data An arbitrary datafield that is passed to the receiver.
* @return `true` is the flash loan was successfull.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes memory data
)
public virtual override returns (bool)
{
uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount);
require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == RETURN_VALUE, "ERC20FlashMint: invalid return value");
uint256 currentAllowance = allowance(address(receiver), address(this));
require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund");
_approve(address(receiver), address(this), currentAllowance - amount - fee);
_burn(address(receiver), amount + fee);
return true;
}
uint256[50] private __gap;
} | 833 | 82 | 1 | 1. [H-01] Missing overflow check in flashLoan (Overflow)
ERC20FlashMintUpgradeable.`flashLoan` does not check for an overflow when adding the fees to the flashloan amount.
`_burn(address(receiver), amount + fee);` | 1 |
30_Controller.sol | // SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IController.sol";
import "../interfaces/IConverter.sol";
import "../interfaces/IVault.sol";
import "../interfaces/IHarvester.sol";
import "../interfaces/IStrategy.sol";
import "../interfaces/IManager.sol";
/**
* @title Controller
* @notice This controller allows multiple strategies to be used
* for a single vault supporting multiple tokens.
*/
contract Controller is IController {
using SafeERC20 for IERC20;
using SafeMath for uint256;
IManager public immutable override manager;
bool public globalInvestEnabled;
uint256 public maxStrategies;
struct VaultDetail {
address converter;
uint256 balance;
address[] strategies;
mapping(address => uint256) balances;
mapping(address => uint256) index;
mapping(address => uint256) caps;
}
// vault => Vault
mapping(address => VaultDetail) internal _vaultDetails;
// strategy => vault
mapping(address => address) internal _vaultStrategies;
/**
* @notice Logged when harvest is called for a strategy
*/
event Harvest(address indexed strategy);
/**
* @notice Logged when a strategy is added for a vault
*/
event StrategyAdded(address indexed vault, address indexed strategy, uint256 cap);
/**
* @notice Logged when a strategy is removed for a vault
*/
event StrategyRemoved(address indexed vault, address indexed strategy);
/**
* @notice Logged when strategies are reordered for a vault
*/
event StrategiesReordered(
address indexed vault,
address indexed strategy1,
address indexed strategy2
);
/**
* @param _manager The address of the manager
*/
constructor(
address _manager
)
public
{
manager = IManager(_manager);
globalInvestEnabled = true;
maxStrategies = 10;
}
/**
* STRATEGIST-ONLY FUNCTIONS
*/
/**
* @notice Adds a strategy for a given vault
* @param _vault The address of the vault
* @param _strategy The address of the strategy
* @param _cap The cap of the strategy
* @param _timeout The timeout between harvests
*/
function addStrategy(
address _vault,
address _strategy,
uint256 _cap,
uint256 _timeout
)
external
notHalted
onlyStrategist
onlyStrategy(_strategy)
{
require(manager.allowedVaults(_vault), "!_vault");
require(_vaultDetails[_vault].converter != address(0), "!converter");
// checking if strategy is already added
require(_vaultStrategies[_strategy] == address(0), "Strategy is already added");
// get the index of the newly added strategy
uint256 index = _vaultDetails[_vault].strategies.length;
// ensure we haven't added too many strategies already
require(index < maxStrategies, "!maxStrategies");
// push the strategy to the array of strategies
_vaultDetails[_vault].strategies.push(_strategy);
// set the cap
_vaultDetails[_vault].caps[_strategy] = _cap;
// set the index
_vaultDetails[_vault].index[_strategy] = index;
// store the mapping of strategy to the vault
_vaultStrategies[_strategy] = _vault;
if (_timeout > 0) {
// add it to the harvester
IHarvester(manager.harvester()).addStrategy(_vault, _strategy, _timeout);
}
emit StrategyAdded(_vault, _strategy, _cap);
}
/**
* @notice Withdraws token from a strategy to the treasury address as returned by the manager
* @param _strategy The address of the strategy
* @param _token The address of the token
*/
function inCaseStrategyGetStuck(
address _strategy,
address _token
)
external
onlyStrategist
{
IStrategy(_strategy).withdraw(_token);
IERC20(_token).safeTransfer(
manager.treasury(),
IERC20(_token).balanceOf(address(this))
);
}
/**
* @notice Withdraws token from the controller to the treasury
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function inCaseTokensGetStuck(
address _token,
uint256 _amount
)
external
onlyStrategist
{
IERC20(_token).safeTransfer(manager.treasury(), _amount);
}
/**
* @notice Removes a strategy for a given token
* @param _vault The address of the vault
* @param _strategy The address of the strategy
* @param _timeout The timeout between harvests
*/
function removeStrategy(
address _vault,
address _strategy,
uint256 _timeout
)
external
notHalted
onlyStrategist
{
require(manager.allowedVaults(_vault), "!_vault");
VaultDetail storage vaultDetail = _vaultDetails[_vault];
// get the index of the strategy to remove
uint256 index = vaultDetail.index[_strategy];
// get the index of the last strategy
uint256 tail = vaultDetail.strategies.length.sub(1);
// get the address of the last strategy
address replace = vaultDetail.strategies[tail];
// replace the removed strategy with the tail
vaultDetail.strategies[index] = replace;
// set the new index for the replaced strategy
vaultDetail.index[replace] = index;
// remove the duplicate replaced strategy
vaultDetail.strategies.pop();
// remove the strategy's index
delete vaultDetail.index[_strategy];
// remove the strategy's cap
delete vaultDetail.caps[_strategy];
// remove the strategy's balance
delete vaultDetail.balances[_strategy];
// remove the mapping of strategy to the vault
delete _vaultStrategies[_strategy];
// pull funds from the removed strategy to the vault
IStrategy(_strategy).withdrawAll();
// remove the strategy from the harvester
IHarvester(manager.harvester()).removeStrategy(_vault, _strategy, _timeout);
emit StrategyRemoved(_vault, _strategy);
}
/**
* @notice Reorders two strategies for a given vault
* @param _vault The address of the vault
* @param _strategy1 The address of the first strategy
* @param _strategy2 The address of the second strategy
*/
function reorderStrategies(
address _vault,
address _strategy1,
address _strategy2
)
external
notHalted
onlyStrategist
{
require(manager.allowedVaults(_vault), "!_vault");
require(_vaultStrategies[_strategy1] == _vault, "!_strategy1");
require(_vaultStrategies[_strategy2] == _vault, "!_strategy2");
VaultDetail storage vaultDetail = _vaultDetails[_vault];
// get the indexes of the strategies
uint256 index1 = vaultDetail.index[_strategy1];
uint256 index2 = vaultDetail.index[_strategy2];
// set the new addresses at their indexes
vaultDetail.strategies[index1] = _strategy2;
vaultDetail.strategies[index2] = _strategy1;
// update indexes
vaultDetail.index[_strategy1] = index2;
vaultDetail.index[_strategy2] = index1;
emit StrategiesReordered(_vault, _strategy1, _strategy2);
}
/**
* @notice Sets/updates the cap of a strategy for a vault
* @dev If the balance of the strategy is greater than the new cap (except if
* the cap is 0), then withdraw the difference from the strategy to the vault.
* @param _vault The address of the vault
* @param _strategy The address of the strategy
* @param _cap The new cap of the strategy
*/
function setCap(
address _vault,
address _strategy,
uint256 _cap,
address _convert
)
external
notHalted
onlyStrategist
onlyStrategy(_strategy)
{
_vaultDetails[_vault].caps[_strategy] = _cap;
uint256 _balance = IStrategy(_strategy).balanceOf();
// send excess funds (over cap) back to the vault
if (_balance > _cap && _cap != 0) {
uint256 _diff = _balance.sub(_cap);
IStrategy(_strategy).withdraw(_diff);
updateBalance(_vault, _strategy);
_balance = IStrategy(_strategy).balanceOf();
_vaultDetails[_vault].balance = _vaultDetails[_vault].balance.sub(_diff);
address _want = IStrategy(_strategy).want();
_balance = IERC20(_want).balanceOf(address(this));
if (_convert != address(0)) {
IConverter _converter = IConverter(_vaultDetails[_vault].converter);
IERC20(_want).safeTransfer(address(_converter), _balance);
_balance = _converter.convert(_want, _convert, _balance, 1);
IERC20(_convert).safeTransfer(_vault, _balance);
} else {
IERC20(_want).safeTransfer(_vault, _balance);
}
}
}
/**
* @notice Sets/updates the converter for a given vault
* @param _vault The address of the vault
* @param _converter The address of the converter
*/
function setConverter(
address _vault,
address _converter
)
external
notHalted
onlyStrategist
{
require(manager.allowedConverters(_converter), "!allowedConverters");
_vaultDetails[_vault].converter = _converter;
}
/**
* @notice Sets/updates the global invest enabled flag
* @param _investEnabled The new bool of the invest enabled flag
*/
function setInvestEnabled(
bool _investEnabled
)
external
notHalted
onlyStrategist
{
globalInvestEnabled = _investEnabled;
}
/**
* @notice Sets/updates the maximum number of strategies for a vault
* @param _maxStrategies The new value of the maximum strategies
*/
function setMaxStrategies(
uint256 _maxStrategies
)
external
notHalted
onlyStrategist
{
maxStrategies = _maxStrategies;
}
function skim(
address _strategy
)
external
onlyStrategist
onlyStrategy(_strategy)
{
address _want = IStrategy(_strategy).want();
IStrategy(_strategy).skim();
IERC20(_want).safeTransfer(_vaultStrategies[_strategy], IERC20(_want).balanceOf(address(this)));
}
/**
* @notice Withdraws all funds from a strategy
* @param _strategy The address of the strategy
* @param _convert The token address to convert to
*/
function withdrawAll(
address _strategy,
address _convert
)
external
override
onlyStrategist
onlyStrategy(_strategy)
{
address _want = IStrategy(_strategy).want();
IStrategy(_strategy).withdrawAll();
uint256 _amount = IERC20(_want).balanceOf(address(this));
address _vault = _vaultStrategies[_strategy];
updateBalance(_vault, _strategy);
if (_convert != address(0)) {
IConverter _converter = IConverter(_vaultDetails[_vault].converter);
IERC20(_want).safeTransfer(address(_converter), _amount);
_amount = _converter.convert(_want, _convert, _amount, 1);
IERC20(_convert).safeTransfer(_vault, _amount);
} else {
IERC20(_want).safeTransfer(_vault, _amount);
}
uint256 _balance = _vaultDetails[_vault].balance;
if (_balance >= _amount) {
_vaultDetails[_vault].balance = _balance.sub(_amount);
} else {
_vaultDetails[_vault].balance = 0;
}
}
/**
* HARVESTER-ONLY FUNCTIONS
*/
/**
* @notice Harvests the specified strategy
* @param _strategy The address of the strategy
*/
function harvestStrategy(
address _strategy,
uint256 _estimatedWETH,
uint256 _estimatedYAXIS
)
external
override
notHalted
onlyHarvester
onlyStrategy(_strategy)
{
uint256 _before = IStrategy(_strategy).balanceOf();
IStrategy(_strategy).harvest(_estimatedWETH, _estimatedYAXIS);
uint256 _after = IStrategy(_strategy).balanceOf();
address _vault = _vaultStrategies[_strategy];
_vaultDetails[_vault].balance = _vaultDetails[_vault].balance.add(_after.sub(_before));
_vaultDetails[_vault].balances[_strategy] = _after;
emit Harvest(_strategy);
}
/**
* VAULT-ONLY FUNCTIONS
*/
/**
* @notice Invests funds into a strategy
* @param _strategy The address of the strategy
* @param _token The address of the token
* @param _amount The amount that will be invested
*/
function earn(
address _strategy,
address _token,
uint256 _amount
)
external
override
notHalted
onlyStrategy(_strategy)
onlyVault(_token)
{
// get the want token of the strategy
address _want = IStrategy(_strategy).want();
if (_want != _token) {
IConverter _converter = IConverter(_vaultDetails[msg.sender].converter);
IERC20(_token).safeTransfer(address(_converter), _amount);
// TODO: do estimation for received
_amount = _converter.convert(_token, _want, _amount, 1);
IERC20(_want).safeTransfer(_strategy, _amount);
} else {
IERC20(_token).safeTransfer(_strategy, _amount);
}
_vaultDetails[msg.sender].balance = _vaultDetails[msg.sender].balance.add(_amount);
// call the strategy deposit function
IStrategy(_strategy).deposit();
updateBalance(msg.sender, _strategy);
}
/**
* @notice Withdraws funds from a strategy
* @dev If the withdraw amount is greater than the first strategy given
* by getBestStrategyWithdraw, this function will loop over strategies
* until the requested amount is met.
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function withdraw(
address _token,
uint256 _amount
)
external
override
onlyVault(_token)
{
(
address[] memory _strategies,
uint256[] memory _amounts
) = getBestStrategyWithdraw(_token, _amount);
for (uint i = 0; i < _strategies.length; i++) {
// getBestStrategyWithdraw will return arrays larger than needed
// if this happens, simply exit the loop
if (_strategies[i] == address(0)) {
break;
}
IStrategy(_strategies[i]).withdraw(_amounts[i]);
updateBalance(msg.sender, _strategies[i]);
address _want = IStrategy(_strategies[i]).want();
if (_want != _token) {
address _converter = _vaultDetails[msg.sender].converter;
IERC20(_want).safeTransfer(_converter, _amounts[i]);
// TODO: do estimation for received
IConverter(_converter).convert(_want, _token, _amounts[i], 1);
}
}
_amount = IERC20(_token).balanceOf(address(this));
_vaultDetails[msg.sender].balance = _vaultDetails[msg.sender].balance.sub(_amount);
IERC20(_token).safeTransfer(msg.sender, _amount);
}
/**
* EXTERNAL VIEW FUNCTIONS
*/
/**
* @notice Returns the rough balance of the sum of all strategies for a given vault
* @dev This function is optimized to prevent looping over all strategy balances,
* and instead the controller tracks the earn, withdraw, and harvest amounts.
*/
function balanceOf()
external
view
override
returns (uint256 _balance)
{
return _vaultDetails[msg.sender].balance;
}
/**
* @notice Returns the converter assigned for the given vault
* @param _vault Address of the vault
*/
function converter(
address _vault
)
external
view
override
returns (address)
{
return _vaultDetails[_vault].converter;
}
/**
* @notice Returns the cap of a strategy for a given vault
* @param _vault The address of the vault
* @param _strategy The address of the strategy
*/
function getCap(
address _vault,
address _strategy
)
external
view
returns (uint256)
{
return _vaultDetails[_vault].caps[_strategy];
}
/**
* @notice Returns whether investing is enabled for the calling vault
* @dev Should be called by the vault
*/
function investEnabled()
external
view
override
returns (bool)
{
if (globalInvestEnabled) {
return _vaultDetails[msg.sender].strategies.length > 0;
}
return false;
}
/**
* @notice Returns all the strategies for a given vault
* @param _vault The address of the vault
*/
function strategies(
address _vault
)
external
view
returns (address[] memory)
{
return _vaultDetails[_vault].strategies;
}
/**
* @notice Returns the length of the strategies of the calling vault
* @dev This function is expected to be called by a vault
*/
function strategies()
external
view
override
returns (uint256)
{
return _vaultDetails[msg.sender].strategies.length;
}
/**
* INTERNAL FUNCTIONS
*/
/**
* @notice Returns the best (optimistic) strategy for funds to be withdrawn from
* @dev Since Solidity doesn't support dynamic arrays in memory, the returned arrays
* from this function will always be the same length as the amount of strategies for
* a token. Check that _strategies[i] != address(0) when consuming to know when to
* break out of the loop.
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function getBestStrategyWithdraw(
address _token,
uint256 _amount
)
internal
view
returns (
address[] memory _strategies,
uint256[] memory _amounts
)
{
// get the length of strategies for a single token
address _vault = manager.vaults(_token);
uint256 k = _vaultDetails[_vault].strategies.length;
// initialize fixed-length memory arrays
_strategies = new address[](k);
_amounts = new uint256[](k);
address _strategy;
uint256 _balance;
// scan forward from the the beginning of strategies
for (uint i = 0; i < k; i++) {
_strategy = _vaultDetails[_vault].strategies[i];
_strategies[i] = _strategy;
// get the balance of the strategy
_balance = _vaultDetails[_vault].balances[_strategy];
// if the strategy doesn't have the balance to cover the withdraw
if (_balance < _amount) {
// withdraw what we can and add to the _amounts
_amounts[i] = _balance;
_amount = _amount.sub(_balance);
} else {
// stop scanning if the balance is more than the withdraw amount
_amounts[i] = _amount;
break;
}
}
}
/**
* @notice Updates the stored balance of a given strategy for a vault
* @param _vault The address of the vault
* @param _strategy The address of the strategy
*/
function updateBalance(
address _vault,
address _strategy
)
internal
{
_vaultDetails[_vault].balances[_strategy] = IStrategy(_strategy).balanceOf();
}
/**
* MODIFIERS
*/
/**
* @notice Reverts if the protocol is halted
*/
modifier notHalted() {
require(!manager.halted(), "halted");
_;
}
/**
* @notice Reverts if the caller is not governance
*/
modifier onlyGovernance() {
require(msg.sender == manager.governance(), "!governance");
_;
}
/**
* @notice Reverts if the caller is not the strategist
*/
modifier onlyStrategist() {
require(msg.sender == manager.strategist(), "!strategist");
_;
}
/**
* @notice Reverts if the strategy is not allowed in the manager
*/
modifier onlyStrategy(address _strategy) {
require(manager.allowedStrategies(_strategy), "!allowedStrategy");
_;
}
/**
* @notice Reverts if the caller is not the harvester
*/
modifier onlyHarvester() {
require(msg.sender == manager.harvester(), "!harvester");
_;
}
/**
* @notice Reverts if the caller is not the vault for the given token
*/
modifier onlyVault(address _token) {
require(msg.sender == manager.vaults(_token), "!vault");
_;
}
} | 4,847 | 683 | 2 | 1. [H-01] Controller.setCap sets wrong vault balance
The Controller.setCap function sets a cap for a strategy and withdraws any excess amounts (_diff). The vault balance is decreased by the entire strategy balance instead of by this `_diff`: `_vaultDetails[_vault].balance = _vaultDetails[_vault].balance.sub(_balance);`
2. [H-02] set cap breaks vault's Balance. L475
In controller.sol's function `setCap`, the contract wrongly handles _vaultDetails[_vault].balance. While the balance should be decreased by the difference of strategies balance, it subtracts the remaining balance of the strategy. See Controller.sol L262-L278. _vaultDetails[_vault].balance = _vaultDetails[_vault].balance.sub(_balance);
3. [H-04] Controller does not raise an error when there's insufficient liquidity (Unchecked external values)
Function `withdraw` and `getBestStrategyWithdraw`
4. [H-06] earn results in decreasing share price. L410-L436
At Vault.sol L293, when a vault calculates its value, it sums up all tokens balance. However, when the controller calculates vaults' value (at Controller.sol L410-L436), it only adds the amount of strategy.want it received. (in this case, it's t3crv).
5. [H-10] An attacker can steal funds from multi-token vaults. L396
Function `harvestStrategy`
6. [M-06] Controller is vulnerable to sandwich attack. (Front-running)
Function `withdraw`
7. [M-08] Controller.inCaseStrategyGetStuck does not update balance (Insecure External Calls)
The Controller.`inCaseStrategyGetStuck` withdraws from a strategy but does not call updateBalance(_vault, _strategy) afterwards.
| 7 |
47_WrappedIbbtcEth.sol | //SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.12;
import "../deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "../deps/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "./ICore.sol";
/*Wrapped Interest-Bearing Bitcoin (Ethereum mainnet variant)
*/
contract WrappedIbbtcEth is Initializable, ERC20Upgradeable {
address public governance;
address public pendingGovernance;
ERC20Upgradeable public ibbtc;
ICore public core;
uint256 public pricePerShare;
uint256 public lastPricePerShareUpdate;
event SetCore(address core);
event SetPricePerShare(uint256 pricePerShare, uint256 updateTimestamp);
event SetPendingGovernance(address pendingGovernance);
event AcceptPendingGovernance(address pendingGovernance);
/// ===== Modifiers =====
modifier onlyPendingGovernance() {
require(msg.sender == pendingGovernance, "onlyPendingGovernance");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance, "onlyGovernance");
_;
}
function initialize(address _governance, address _ibbtc, address _core) public initializer {
__ERC20_init("Wrapped Interest-Bearing Bitcoin", "wibBTC");
governance = _governance;
core = ICore(_core);
ibbtc = ERC20Upgradeable(_ibbtc);
updatePricePerShare();
emit SetCore(_core);
}
/// ===== Permissioned: Governance =====
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
pendingGovernance = _pendingGovernance;
emit SetPendingGovernance(pendingGovernance);
}
/// @dev The ibBTC token is technically capable of having it's Core contract changed via governance process. This allows the wrapper to adapt.
/// @dev This function should be run atomically with setCore() on ibBTC if that eventuality ever arises.
function setCore(address _core) external onlyGovernance {
core = ICore(_core);
emit SetCore(_core);
}
/// ===== Permissioned: Pending Governance =====
function acceptPendingGovernance() external onlyPendingGovernance {
governance = pendingGovernance;
emit AcceptPendingGovernance(pendingGovernance);
}
/// ===== Permissionless Calls =====
/// @dev Update live ibBTC price per share from core
/// @dev We cache this to reduce gas costs of mint / burn / transfer operations.
/// @dev Update function is permissionless, and must be updated at least once every X time as a sanity check to ensure value is up-to-date
function updatePricePerShare() public virtual returns (uint256) {
pricePerShare = core.pricePerShare();
lastPricePerShareUpdate = now;
emit SetPricePerShare(pricePerShare, lastPricePerShareUpdate);
}
/// @dev Deposit ibBTC to mint wibBTC shares
function mint(uint256 _shares) external {
require(ibbtc.transferFrom(_msgSender(), address(this), _shares));
_mint(_msgSender(), _shares);
}
/// @dev Redeem wibBTC for ibBTC. Denominated in shares.
function burn(uint256 _shares) external {
_burn(_msgSender(), _shares);
require(ibbtc.transfer(_msgSender(), _shares));
}
/// ===== Transfer Overrides =====
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
/// The _balances mapping represents the underlying ibBTC shares ("non-rebased balances")
/// Some naming confusion emerges due to maintaining original ERC20 var names
uint256 amountInShares = balanceToShares(amount);
_transfer(sender, recipient, amountInShares);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amountInShares, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
/// The _balances mapping represents the underlying ibBTC shares ("non-rebased balances")
/// Some naming confusion emerges due to maintaining original ERC20 var names
uint256 amountInShares = balanceToShares(amount);
_transfer(_msgSender(), recipient, amountInShares);
return true;
}
/// ===== View Methods =====
/// @dev Wrapped ibBTC shares of account
function sharesOf(address account) public view returns (uint256) {
return _balances[account];
}
/// @dev Current account shares * pricePerShare
function balanceOf(address account) public view override returns (uint256) {
return sharesOf(account).mul(pricePerShare).div(1e18);
}
/// @dev Total wrapped ibBTC shares
function totalShares() public view returns (uint256) {
return _totalSupply;
}
/// @dev Current total shares * pricePerShare
function totalSupply() public view override returns (uint256) {
return totalShares().mul(pricePerShare).div(1e18);
}
function balanceToShares(uint256 balance) public view returns (uint256) {
return balance.mul(1e18).div(pricePerShare);
}
function sharesToBalance(uint256 shares) public view returns (uint256) {
return shares.mul(pricePerShare).div(1e18);
}
} | 1,336 | 162 | 2 | 1. [H-03] WrappedIbbtcEth contract will use stalled price for `mint/burn` if `updatePricePerShare` wasn't run properly. (Price manipulation)
WrappedIbbtcEth updates `pricePerShare` variable by externally run `updatePricePerShare` function. The variable is then used in mint/burn/transfer functions without any additional checks, even if outdated/stalled. This can happen if the external function wasn't run for any reason.
2. [H-04] WrappedIbbtc and WrappedIbbtcEth contracts do not filter out price feed outliers. L72 L75
In WrappedIbbtcEth `pricePerShare` variable is updated by externally run `updatePricePerShare` function (WrappedIbbtcEth.sol L72), and then used in mint/burn/transfer functions without additional checks via `balanceToShares` function.
3. [M-02] Null check in `pricePerShare`. (DoS)
oracle can 0 as a price of the share, in that case, 0 will be the denominator in some calculations which can cause `reverts` from SafeMath (for e.g here: WrappedIbbtc.sol L148) resulting in Denial Of Service.
4. [M-04] No sanity check on pricePerShare might lead to lost value. (Unchecked return values)
The transfer function calculates the amount to send by calling balanceToShares | 4 |
23_nTokenAction.sol | // SPDX-License-Identifier: GPL-3.0-only
pragma solidity >0.7.0;
pragma experimental ABIEncoderV2;
import "../../internal/nTokenHandler.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/balances/Incentives.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "interfaces/notional/nTokenERC20.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract nTokenAction is StorageLayoutV1, nTokenERC20 {
using BalanceHandler for BalanceState;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Total number of tokens in circulation
/// @param nTokenAddress The address of the nToken
/// @return totalSupply number of tokens held
function nTokenTotalSupply(address nTokenAddress)
external
view
override
returns (uint256 totalSupply)
{
// prettier-ignore
(
totalSupply,
/* integralTotalSupply */,
/* lastSupplyChangeTime */
) = nTokenHandler.getStoredNTokenSupplyFactors(nTokenAddress);
}
/// @notice Get the number of tokens held by the `account`
/// @param account The address of the account to get the balance of
/// @return The number of tokens held
function nTokenBalanceOf(uint16 currencyId, address account)
external
view
override
returns (uint256)
{
// prettier-ignore
(
/* int cashBalance */,
int256 nTokenBalance,
/* uint lastClaimTime */,
/* uint lastClaimIntegralSupply */
) = BalanceHandler.getBalanceStorage(account, currencyId);
require(nTokenBalance >= 0);
// dev: negative nToken balance
return uint256(nTokenBalance);
}
/// @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
/// @param owner The address of the account holding the funds
/// @param spender The address of the account spending the funds
/// @return The number of tokens approved
function nTokenTransferAllowance(
uint16 currencyId,
address owner,
address spender
) external view override returns (uint256) {
// This whitelist allowance supersedes any specific allowances
uint256 allowance = nTokenWhitelist[owner][spender];
if (allowance > 0) return allowance;
return nTokenAllowance[owner][spender][currencyId];
}
/// @notice Approve `spender` to transfer up to `amount` from `src`
/// @dev Can only be called via the nToken proxy
/// @param spender The address of the account which may transfer tokens
/// @param amount The number of tokens that are approved (2^256-1 means infinite)
/// @return Whether or not the approval succeeded
function nTokenTransferApprove(
uint16 currencyId,
address owner,
address spender,
uint256 amount
) external override returns (bool) {
address nTokenAddress = nTokenHandler.nTokenAddress(currencyId);
require(msg.sender == nTokenAddress, "Unauthorized caller");
nTokenAllowance[owner][spender][currencyId] = amount;
return true;
}
/// @notice Transfer `amount` tokens from `msg.sender` to `dst`
/// @dev Can only be called via the nToken proxy
/// @param from The address of the destination account
/// @param amount The number of tokens to transfer
/// @return Whether or not the transfer succeeded
function nTokenTransfer(
uint16 currencyId,
address from,
address to,
uint256 amount
) external override returns (bool) {
address nTokenAddress = nTokenHandler.nTokenAddress(currencyId);
require(msg.sender == nTokenAddress, "Unauthorized caller");
return _transfer(currencyId, from, to, amount);
}
/// @notice Transfer `amount` tokens from `src` to `dst`
/// @dev Can only be called via the nToken proxy
/// @param currencyId Currency id of the nToken
/// @param spender The address of the original caller
/// @param from The address of the source account
/// @param to The address of the destination account
/// @param amount The number of tokens to transfer
/// @return Whether or not the transfer succeeded
function nTokenTransferFrom(
uint16 currencyId,
address spender,
address from,
address to,
uint256 amount
) external override returns (bool, uint256) {
address nTokenAddress = nTokenHandler.nTokenAddress(currencyId);
require(msg.sender == nTokenAddress, "Unauthorized caller");
uint256 allowance = nTokenWhitelist[from][spender];
if (allowance > 0) {
// This whitelist allowance supersedes any specific allowances
require(allowance >= amount, "Insufficient allowance");
allowance = allowance.sub(amount);
nTokenWhitelist[from][spender] = allowance;
} else {
// This is the specific allowance for the nToken.
allowance = nTokenAllowance[from][spender][currencyId];
require(allowance >= amount, "Insufficient allowance");
allowance = allowance.sub(amount);
nTokenAllowance[from][spender][currencyId] = allowance;
}
bool success = _transfer(currencyId, from, to, amount);
return (success, allowance);
}
/// @notice Will approve all nToken transfers to the specific sender. This is used for simplifying UX, a user can approve
/// all token transfers to an external exchange or protocol in a single txn. This must be called directly
/// on the Notional contract, not available via the ERC20 proxy.
/// @dev emit:Approval
/// @param spender The address of the account which may transfer tokens
/// @param amount The number of tokens that are approved (2^256-1 means infinite)
/// @return Whether or not the approval succeeded
function nTokenTransferApproveAll(address spender, uint256 amount)
external
override
returns (bool)
{
nTokenWhitelist[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @notice Claims incentives accrued on all nToken balances and transfers them to the msg.sender
/// @dev auth:msg.sender
/// @return Total amount of incentives claimed
function nTokenClaimIncentives() external override returns (uint256) {
address account = msg.sender;
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
uint256 totalIncentivesClaimed;
BalanceState memory balanceState;
if (accountContext.bitmapCurrencyId != 0) {
balanceState.loadBalanceState(account, accountContext.bitmapCurrencyId, accountContext);
if (balanceState.storedNTokenBalance > 0) {
totalIncentivesClaimed = totalIncentivesClaimed.add(
BalanceHandler.claimIncentivesManual(balanceState, account)
);
}
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
uint256 currencyId = uint256(uint16(bytes2(currencies) & Constants.UNMASK_FLAGS));
balanceState.loadBalanceState(account, currencyId, accountContext);
if (balanceState.storedNTokenBalance > 0) {
totalIncentivesClaimed = totalIncentivesClaimed.add(
BalanceHandler.claimIncentivesManual(balanceState, account)
);
}
currencies = currencies << 16;
}
// NOTE: no need to set account context after claiming incentives
return totalIncentivesClaimed;
}
/// @notice Returns the present value of the nToken's assets denominated in asset tokens
function nTokenPresentValueAssetDenominated(uint16 currencyId)
external
view
override
returns (int256)
{
// prettier-ignore
(
int256 totalAssetPV,
/* portfolio */
) = _getNTokenPV(currencyId);
return totalAssetPV;
}
/// @notice Returns the present value of the nToken's assets denominated in underlying
function nTokenPresentValueUnderlyingDenominated(uint16 currencyId)
external
view
override
returns (int256)
{
(int256 totalAssetPV, nTokenPortfolio memory nToken) = _getNTokenPV(currencyId);
return nToken.cashGroup.assetRate.convertToUnderlying(totalAssetPV);
}
function _getNTokenPV(uint256 currencyId)
private
view
returns (int256, nTokenPortfolio memory)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nTokenHandler.loadNTokenPortfolioView(currencyId, nToken);
// prettier-ignore
(
int256 totalAssetPV,
/* ifCashMapping */
) = nTokenHandler.getNTokenAssetPV(nToken, blockTime);
return (totalAssetPV, nToken);
}
/// @notice Transferring tokens will also claim incentives at the same time
function _transfer(
uint256 currencyId,
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
{
// prettier-ignore
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* parameters */
) = nTokenHandler.getNTokenContext(recipient);
// nTokens cannot hold nToken balances
require(isNToken == 0, "Cannot transfer to nToken");
}
AccountContext memory senderContext = AccountContextHandler.getAccountContext(sender);
BalanceState memory senderBalance;
senderBalance.loadBalanceState(sender, currencyId, senderContext);
AccountContext memory recipientContext = AccountContextHandler.getAccountContext(recipient);
BalanceState memory recipientBalance;
recipientBalance.loadBalanceState(recipient, currencyId, recipientContext);
int256 amountInt = SafeCast.toInt256(amount);
senderBalance.netNTokenTransfer = amountInt.neg();
recipientBalance.netNTokenTransfer = amountInt;
senderBalance.finalize(sender, senderContext, false);
recipientBalance.finalize(recipient, recipientContext, false);
senderContext.setAccountContext(sender);
recipientContext.setAccountContext(recipient);
emit Transfer(sender, recipient, amount);
return true;
}
} | 2,311 | 292 | 1 | 1. [H-01] Self transfer can lead to unlimited mint. (Unchecked return values, reentrancy)
The implementation of the `_transfer` function in nTokenAction.sol is different from the usual erc20 token transfer function. | 1 |
67_Vault.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {Counters} from "@openzeppelin/contracts/utils/Counters.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {Trust} from "@rari-capital/solmate/src/auth/Trust.sol";
import {IVault} from "./vault/IVault.sol";
import {IVaultSponsoring} from "./vault/IVaultSponsoring.sol";
import {PercentMath} from "./lib/PercentMath.sol";
import {Depositors} from "./vault/Depositors.sol";
import {Claimers} from "./vault/Claimers.sol";
import {IIntegration} from "./integrations/IIntegration.sol";
import {IStrategy} from "./strategy/IStrategy.sol";
import {ERC165Query} from "./lib/ERC165Query.sol";
import "hardhat/console.sol";
/**
* A vault where other accounts can deposit an underlying token
* currency and set distribution params for their principal and yield
*
* @dev Yield generation strategies not yet implemented
*/
contract Vault is IVault, IVaultSponsoring, Context, ERC165, Trust {
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
using PercentMath for uint256;
using Address for address;
using ERC165Query for address;
//
// Constants
//
uint256 public constant MIN_SPONSOR_LOCK_DURATION = 1209600;
// 2 weeks in seconds
uint256 public constant SHARES_MULTIPLIER = 10**18;
//
// State
//
/// Underlying ERC20 token accepted by the vault
/// See {IVault}
IERC20 public override(IVault) underlying;
/// See {IVault}
IStrategy public strategy;
/// See {IVault}
uint256 public investPerc;
/// See {IVault}
uint256 public immutable override(IVault) minLockPeriod;
/// See {IVaultSponsoring}
uint256 public override(IVaultSponsoring) totalSponsored;
/// Depositors, represented as an NFT per deposit
Depositors public depositors;
/// Yield allocation
Claimers public claimers;
/// Unique IDs to correlate donations that belong to the same foundation
Counters.Counter private _depositGroupIds;
/**
* @param _underlying Underlying ERC20 token to use.
*/
constructor(
IERC20 _underlying,
uint256 _minLockPeriod,
uint256 _investPerc,
address _owner
) Trust(_owner) {
require(
PercentMath.validPerc(_investPerc),
"Vault: invalid investPerc"
);
require(
address(_underlying) != address(0x0),
"VaultContext: underlying cannot be 0x0"
);
investPerc = _investPerc;
underlying = _underlying;
minLockPeriod = _minLockPeriod;
depositors = new Depositors(address(this), "depositors", "p");
claimers = new Claimers(address(this));
}
//
// IVault
//
/// See {IVault}
function setStrategy(address _strategy)
external
override(IVault)
requiresTrust
{
require(_strategy != address(0), "Vault: strategy 0x");
require(
IStrategy(_strategy).vault() == address(this),
"Vault: invalid vault"
);
require(
address(strategy) == address(0) || strategy.investedAssets() == 0,
"Vault: strategy has invested funds"
);
strategy = IStrategy(_strategy);
}
/// See {IVault}
function totalUnderlying() public view override(IVault) returns (uint256) {
if (address(strategy) != address(0)) {
return
underlying.balanceOf(address(this)) + strategy.investedAssets();
} else {
return underlying.balanceOf(address(this));
}
}
/// See {IVault}
function totalShares() public view override(IVault) returns (uint256) {
return claimers.totalShares();
}
/// See {IVault}
function yieldFor(address _to)
public
view
override(IVault)
returns (uint256)
{
uint256 tokenId = claimers.addressToTokenID(_to);
uint256 claimerPrincipal = claimers.principalOf(tokenId);
uint256 claimerShares = claimers.sharesOf(tokenId);
uint256 currentClaimerPrincipal = _computeAmount(
claimerShares,
totalShares(),
totalUnderlyingMinusSponsored()
);
if (currentClaimerPrincipal <= claimerPrincipal) {
return 0;
}
return currentClaimerPrincipal - claimerPrincipal;
}
/// See {IVault}
function deposit(DepositParams calldata _params) external {
_createDeposit(_params.amount, _params.lockedUntil, _params.claims);
_transferAndCheckUnderlying(_msgSender(), _params.amount);
}
/// See {IVault}
function claimYield(address _to) external override(IVault) {
uint256 yield = yieldFor(_msgSender());
if (yield == 0) return;
uint256 shares = _computeShares(
yield,
totalShares(),
totalUnderlyingMinusSponsored()
);
uint256 sharesAmount = _computeAmount(
shares,
totalShares(),
totalUnderlyingMinusSponsored()
);
claimers.claimYield(_msgSender(), _to, sharesAmount, shares);
underlying.safeTransfer(_to, sharesAmount);
}
/// See {IVault}
function withdraw(address _to, uint256[] memory _ids)
external
override(IVault)
{
_withdraw(_to, _ids, false);
}
/// See {IVault}
function forceWithdraw(address _to, uint256[] memory _ids) external {
_withdraw(_to, _ids, true);
}
/// See {IVault}
function setInvestPerc(uint16 _investPerc) external requiresTrust {
require(
PercentMath.validPerc(_investPerc),
"Vault: invalid investPerc"
);
emit InvestPercentageUpdated(_investPerc);
investPerc = _investPerc;
}
/// See {IVault}
function investableAmount() public view returns (uint256) {
uint256 maxInvestableAssets = totalUnderlying().percOf(investPerc);
uint256 alreadyInvested = strategy.investedAssets();
if (alreadyInvested >= maxInvestableAssets) {
return 0;
} else {
return maxInvestableAssets - alreadyInvested;
}
}
/// See {IVault}
function updateInvested() external requiresTrust {
require(address(strategy) != address(0), "Vault: strategy is not set");
uint256 _investable = investableAmount();
if (_investable > 0) {
underlying.safeTransfer(address(strategy), _investable);
emit Invested(_investable);
}
strategy.doHardWork();
}
//
// IVaultSponsoring
/// See {IVaultSponsoring}
function sponsor(uint256 _amount, uint256 _lockedUntil)
external
override(IVaultSponsoring)
{
if (_lockedUntil == 0)
_lockedUntil = block.timestamp + MIN_SPONSOR_LOCK_DURATION;
else
require(
_lockedUntil >= block.timestamp + MIN_SPONSOR_LOCK_DURATION,
"Vault: lock time is too small"
);
uint256 tokenId = depositors.mint(
_msgSender(),
_amount,
0,
_lockedUntil
);
emit Sponsored(tokenId, _amount, _msgSender(), _lockedUntil);
totalSponsored += _amount;
_transferAndCheckUnderlying(_msgSender(), _amount);
}
/// See {IVaultSponsoring}
function unsponsor(address _to, uint256[] memory _ids) external {
_unsponsor(_to, _ids, false);
}
/// See {IVaultSponsoring}
function forceUnsponsor(address _to, uint256[] memory _ids) external {
_unsponsor(_to, _ids, true);
}
//
// Public API
//
/**
* Computes the total amount of principal + yield currently controlled by the
* vault and the strategy. The principal + yield is the total amount
* of underlying that can be claimed or withdrawn, excluding the sponsored amount.
*
* @return Total amount of principal and yield help by the vault (not including sponsored amount).
*/
function totalUnderlyingMinusSponsored() public view returns (uint256) {
// TODO no invested amount yet
return totalUnderlying() - totalSponsored;
}
//
// ERC165
//
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165)
returns (bool)
{
return
interfaceId == type(IVault).interfaceId ||
interfaceId == type(IVaultSponsoring).interfaceId ||
super.supportsInterface(interfaceId);
}
//
// Internal API
//
/**
* Withdraws the principal from the deposits with the ids provided in @param _ids and sends it to @param _to.
*
* @notice the NFTs of the deposits will be burned.
*
* @param _to Address that will receive the funds.
* @param _ids Array with the ids of the deposits.
* @param _force Boolean to specify if the action should be perfomed when there's loss.
*/
function _withdraw(
address _to,
uint256[] memory _ids,
bool _force
) internal {
uint256 localTotalShares = totalShares();
uint256 localTotalPrincipal = totalUnderlyingMinusSponsored();
uint256 amount;
for (uint8 i = 0; i < _ids.length; i++) {
amount += _withdrawDeposit(
_ids[i],
localTotalShares,
localTotalPrincipal,
_to,
_force
);
}
underlying.safeTransfer(_to, amount);
}
/**
* Withdraws the sponsored amount for the deposits with the ids provided
* in @param _ids and sends it to @param _to.
*
* @notice the NFTs of the deposits will be burned.
*
* @param _to Address that will receive the funds.
* @param _ids Array with the ids of the deposits.
* @param _force Boolean to specify if the action should be perfomed when there's loss.
*/
function _unsponsor(
address _to,
uint256[] memory _ids,
bool _force
) internal {
uint256 sponsorAmount;
for (uint8 i = 0; i < _ids.length; i++) {
uint256 tokenId = _ids[i];
require(
depositors.ownerOf(tokenId) == _msgSender(),
"Vault: you are not the owner of a sponsor"
);
(
uint256 depositAmount,
uint256 claimerId,
uint256 lockedUntil
) = depositors.deposits(tokenId);
require(lockedUntil <= block.timestamp, "Vault: amount is locked");
require(claimerId == 0, "Vault: token id is not a sponsor");
depositors.burn(tokenId);
emit Unsponsored(tokenId);
sponsorAmount += depositAmount;
}
uint256 sponsorToTransfer = sponsorAmount;
if (_force && sponsorAmount > totalUnderlying()) {
sponsorToTransfer = totalUnderlying();
} else if (!_force) {
require(
sponsorToTransfer <= totalUnderlying(),
"Vault: not enough funds to unsponsor"
);
}
totalSponsored -= sponsorAmount;
underlying.safeTransfer(_to, sponsorToTransfer);
}
/**
* Creates a deposit with the given amount of underlying and claim
* structure. The deposit is locked until the timestamp specified in @param _lockedUntil.
* @notice This function assumes underlying will be transfered elsewhere in
* the transaction.
*
* @notice Underlying must be transfered *after* this function, in order to
* correctly calculate shares.
*
* @notice claims must add up to 100%.
*
* @param _amount Amount of underlying to consider @param claims claim
* @param _lockedUntil When the depositor can unsponsor the amount.
* @param claims Claim params
* params.
*/
function _createDeposit(
uint256 _amount,
uint256 _lockedUntil,
ClaimParams[] calldata claims
) internal {
if (_lockedUntil == 0) _lockedUntil = block.timestamp + minLockPeriod;
else
require(
_lockedUntil >= block.timestamp + minLockPeriod,
"Vault: lock time is too small"
);
uint256 localTotalShares = totalShares();
uint256 localTotalUnderlying = totalUnderlyingMinusSponsored();
uint256 pct = 0;
for (uint256 i = 0; i < claims.length; ++i) {
ClaimParams memory data = claims[i];
_createClaim(
_depositGroupIds.current(),
_amount,
_lockedUntil,
data,
localTotalShares,
localTotalUnderlying
);
pct += data.pct;
}
_depositGroupIds.increment();
require(pct.is100Perc(), "Vault: claims don't add up to 100%");
}
function _createClaim(
uint256 _depositGroupId,
uint256 _amount,
uint256 _lockedUntil,
ClaimParams memory _claim,
uint256 _localTotalShares,
uint256 _localTotalPrincipal
) internal {
uint256 amount = _amount.percOf(_claim.pct);
uint256 newShares = _computeShares(
amount,
_localTotalShares,
_localTotalPrincipal
);
uint256 claimerId = claimers.mint(
_claim.beneficiary,
amount,
newShares
);
uint256 tokenId = depositors.mint(
_msgSender(),
amount,
claimerId,
_lockedUntil
);
if (_isIntegration(_claim.beneficiary)) {
bytes4 ret = IIntegration(_claim.beneficiary).onDepositMinted(
tokenId,
newShares,
_claim.data
);
require(
ret == IIntegration(_claim.beneficiary).onDepositMinted.selector
);
}
emit DepositMinted(
tokenId,
_depositGroupId,
amount,
newShares,
_msgSender(),
_claim.beneficiary,
claimerId,
_lockedUntil
);
}
/**
* Burns a deposit NFT and reduces the principal and shares of the claimer.
* If there were any yield to be claimed, the claimer will also keep shares to withdraw later on.
*
* @notice This function doesn't transfer any funds, it only updates the state.
*
* @notice Only the owner of the deposit may call this function.
*
* @param _tokenId The deposit ID to withdraw from.
* @param _totalShares The total shares to consider for the withdraw.
* @param _totalUnderlyingMinusSponsored The total underlying to consider for the withdraw.
*
* @return the amount to withdraw.
*/
function _withdrawDeposit(
uint256 _tokenId,
uint256 _totalShares,
uint256 _totalUnderlyingMinusSponsored,
address _to,
bool _force
) internal returns (uint256) {
require(
depositors.ownerOf(_tokenId) == _msgSender(),
"Vault: you are not the owner of a deposit"
);
(
uint256 depositAmount,
uint256 claimerId,
uint256 lockedUntil
) = depositors.deposits(_tokenId);
require(lockedUntil <= block.timestamp, "Vault: deposit is locked");
require(claimerId != 0, "Vault: token id is not a withdraw");
uint256 claimerShares = claimers.sharesOf(claimerId);
uint256 depositShares = _computeShares(
depositAmount,
_totalShares,
_totalUnderlyingMinusSponsored
);
if (_force && depositShares > claimerShares) {
depositShares = claimerShares;
} else if (!_force) {
require(
claimerShares >= depositShares,
"Vault: cannot withdraw more than the available amount"
);
}
claimers.onWithdraw(claimerId, depositAmount, depositShares);
depositors.burn(_tokenId);
address claimer = claimers.ownerOf(claimerId);
if (_isIntegration(claimer)) {
bytes4 ret = IIntegration(claimer).onDepositBurned(_tokenId);
require(ret == IIntegration(claimer).onDepositBurned.selector);
}
emit DepositBurned(_tokenId, depositShares, _to);
return
_computeAmount(
depositShares,
_totalShares,
_totalUnderlyingMinusSponsored
);
}
function _transferAndCheckUnderlying(address _from, uint256 _amount)
internal
{
uint256 balanceBefore = totalUnderlying();
underlying.safeTransferFrom(_from, address(this), _amount);
uint256 balanceAfter = totalUnderlying();
require(
balanceAfter == balanceBefore + _amount,
"Vault: amount received does not match params"
);
}
function _blockTimestamp() public view returns (uint64) {
return uint64(block.timestamp);
}
/**
* Computes amount of shares that will be received for a given deposit amount
*
* @param _amount Amount of deposit to consider.
* @param _totalShares Amount of existing shares to consider.
* @param _totalUnderlyingMinusSponsored Amounf of existing underlying to consider.
* @return Amount of shares the deposit will receive.
*/
function _computeShares(
uint256 _amount,
uint256 _totalShares,
uint256 _totalUnderlyingMinusSponsored
) internal pure returns (uint256) {
if (_amount == 0) return 0;
if (_totalShares == 0) return _amount * SHARES_MULTIPLIER;
require(
_totalUnderlyingMinusSponsored > 0,
"Vault: cannot compute shares when there's no principal"
);
return (_amount * _totalShares) / _totalUnderlyingMinusSponsored;
}
/**
* Computes the amount of underlying from a given number of shares
*
* @param _shares Number of shares.
* @param _totalShares Amount of existing shares to consider.
* @param _totalUnderlyingMinusSponsored Amounf of existing underlying to consider.
* @return Amount that corresponds to the number of shares.
*/
function _computeAmount(
uint256 _shares,
uint256 _totalShares,
uint256 _totalUnderlyingMinusSponsored
) internal pure returns (uint256) {
if (_totalShares == 0 || _totalUnderlyingMinusSponsored == 0) {
return 0;
} else {
// TODO exclude sponsored assets
return ((_totalUnderlyingMinusSponsored * _shares) / _totalShares);
}
}
/**
* Checks if the given address is a contract implementing IIntegration
*
* @param addr Address to check
* @return true if contract is an IIntegraiont
*/
function _isIntegration(address addr) internal view returns (bool) {
return
addr.doesContractImplementInterface(type(IIntegration).interfaceId);
}
} | 4,420 | 654 | 5 | 1. [H-01] forceUnsponsor() may open a window for attackers to manipulate the _totalShares and freeze users' funds at a certain deposit amount (Access control)
In function `forceUnsponsor()`
2. [H-02] Reentrancy, Withdrawers can get more value returned than expected with reentrant call (Reentrancy)
Function `_withdrawDeposit() ` and `_computeShares()`
3. [H-04] deposit() function is open to reentrancy attacks. (Reentrancy)
4. [H-05] sponsor() function in open to reentrancy attacks. (Reentrancy)
5. [M-01] Late users will take more losses than expected when the underlying contract (EthAnchor) suffers investment losses.
6. [M-04] `unsponsor`, `claimYield` and `withdraw` might fail unexpectedly.
7. [M-06] `totalUnderlyingMinusSponsored()` may revert on underflow and malfunction the contract. (Overflow)
8. [M-07] Vault can't receive deposits if underlying token charges fees on transfer L583
9. [M-09] no use of safeMint() as safe guard for users. L470 L256
In Vault.sol the `deposit()` function eventually calls claimers.mint() and depositers.mint(). Calling mint this way does not ensure that the receiver of the NFT is able to accept them. \_safeMint() should be used with reentrancy guards as a guard to protect the user as it checks to see if a user can properly accept an NFT and reverts otherwise. | 9 |
83_StakingRewards.sol | // SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./MasterChef.sol";
contract StakingRewards is Ownable, ReentrancyGuard, Pausable {
using SafeERC20 for IERC20;
MasterChef public immutable masterChef;
/* ========== STATE VARIABLES ========== */
IERC20 public rewardsToken;
IERC20 public stakingToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 7 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
address public rewardsDistribution;
/* ========== CONSTRUCTOR ========== */
constructor(
address _rewardsDistribution,
address _rewardsToken,
address _stakingToken,
MasterChef _masterChef
) {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
rewardsDistribution = _rewardsDistribution;
masterChef = _masterChef;
}
/* ========== VIEWS ========== */
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
(((lastTimeRewardApplicable() - lastUpdateTime) *
rewardRate *
1e18) / _totalSupply);
}
function earned(address account) public view returns (uint256) {
return
(_balances[account] *
(rewardPerToken() - userRewardPerTokenPaid[account])) /
1e18 +
rewards[account];
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate * rewardsDuration;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256 amount)
external
nonReentrant
whenNotPaused
updateReward(msg.sender)
{
require(amount > 0, "Cannot stake 0");
_totalSupply += amount;
_balances[msg.sender] += amount;
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 pid = masterChef.pid(address(stakingToken));
masterChef.deposit(msg.sender, pid, amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, "Cannot withdraw 0");
_totalSupply -= amount;
_balances[msg.sender] -= amount;
stakingToken.safeTransfer(msg.sender, amount);
uint256 pid = masterChef.pid(address(stakingToken));
masterChef.withdraw(msg.sender, pid, amount);
emit Withdrawn(msg.sender, amount);
}
function getReward() public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}
/* ========== RESTRICTED FUNCTIONS ========== */
function notifyRewardAmount(uint256 reward)
external
updateReward(address(0))
{
require(
msg.sender == rewardsDistribution,
"Caller is not RewardsDistribution contract"
);
if (block.timestamp >= periodFinish) {
rewardRate = reward / rewardsDuration;
} else {
uint256 remaining = periodFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
rewardRate = (reward + leftover) / rewardsDuration;
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(
rewardRate <= balance / rewardsDuration,
"Provided reward too high"
);
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp + rewardsDuration;
emit RewardAdded(reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount)
external
onlyOwner
{
require(
tokenAddress != address(stakingToken),
"Cannot withdraw the staking token"
);
IERC20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(
block.timestamp > periodFinish,
"Previous rewards period must be complete before changing the duration for the new period"
);
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
function setRewardsDistribution(address _rewardsDistribution)
external
onlyOwner
{
require(
block.timestamp > periodFinish,
"Previous rewards period must be complete before changing the duration for the new period"
);
rewardsDistribution = _rewardsDistribution;
emit RewardsDistributionUpdated(rewardsDistribution);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event RewardsDistributionUpdated(address indexed newDistribution);
event Recovered(address token, uint256 amount);
} | 1,501 | 221 | 1 | 1. [H-04] ConvexStakingWrapper, StakingRewards Wrong implementation will send concur rewards to the wrong receiver L99
ConvexStakingWrapper, StakingRewards is using `masterChef.deposit()`, `masterChef.withdraw()`, and these two functions on masterChef will take _msgSender() as the user address, which is actually the address of ConvexStakingWrapper and StakingRewards.
2. [M-06] StakingRewards.sol `recoverERC20()` can be used as a backdoor by the owner to retrieve rewardsToken. (Centralized Control)
3. [M-09] StakingRewards.sol#`notifyRewardAmount()` Improper reward balance checks can make some users unable to withdraw their rewards. L154
4. [M-13] StakingRewards.recoverERC20 allows owner to rug the rewardsToken. (Centralization Risk, ownership)
5. [M-22] If The Staking Token Exists In Both StakingRewards.sol And ConvexStakingWrapper.sol Then It Will Be Possible To Continue Claiming Concur Rewards After The Shelter Has Been Activated
6. [M-23] Transfer to treasury can register as succeeded when failing in `_calcRewardIntegral`. L126
7. [M-26] StakingRewards.`setRewardsDuration` allows setting near zero or enormous rewardsDuration, which breaks reward logic (Lack of Input Validation)
8. [M-30] StakingRewards reward rate can be dragged out and diluted (Timestamp manipulation)
The StakingRewards.`notifyRewardAmount` function receives a reward amount and extends the current reward end time to now + rewardsDuration. | 8 |
28_PostAuctionLauncher.sol | pragma solidity 0.6.12;
//----------------------------------------------------------------------------------
// I n s t a n t
//
// .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo.
// .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo.
// .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO:
// .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO'
// 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO'
//
//----------------------------------------------------------------------------------
//
// Chef Gonpachi's Post Auction Launcher
//
// A post auction contract that takes the proceeds and creates a liquidity pool
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// Made for Sushi.com
//
// Enjoy. (c) Chef Gonpachi
// <https://github.com/chefgonpachi/MISO/>
//
// ---------------------------------------------------------------------
// SPDX-License-Identifier: GPL-3.0
// ---------------------------------------------------------------------
import "../OpenZeppelin/utils/ReentrancyGuard.sol";
import "../Access/MISOAccessControls.sol";
import "../Utils/SafeTransfer.sol";
import "../Utils/BoringMath.sol";
import "../UniswapV2/UniswapV2Library.sol";
import "../UniswapV2/interfaces/IUniswapV2Pair.sol";
import "../UniswapV2/interfaces/IUniswapV2Factory.sol";
import "../interfaces/IWETH9.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IMisoAuction.sol";
contract PostAuctionLauncher is MISOAccessControls, SafeTransfer, ReentrancyGuard {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringMath64 for uint64;
using BoringMath32 for uint32;
using BoringMath16 for uint16;
/// @notice Number of seconds per day.
uint256 private constant SECONDS_PER_DAY = 24 * 60 * 60;
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 private constant LIQUIDITY_PRECISION = 10000;
/// @notice MISOLiquidity template id.
uint256 public constant liquidityTemplate = 3;
/// @notice First Token address.
IERC20 public token1;
/// @notice Second Token address.
IERC20 public token2;
/// @notice Uniswap V2 factory address.
IUniswapV2Factory public factory;
/// @notice WETH contract address.
address private immutable weth;
/// @notice LP pair address.
address public tokenPair;
/// @notice Withdraw wallet address.
address public wallet;
/// @notice Token market contract address.
IMisoAuction public market;
struct LauncherInfo {
uint32 locktime;
uint64 unlock;
uint16 liquidityPercent;
bool launched;
uint128 liquidityAdded;
}
LauncherInfo public launcherInfo;
/// @notice Emitted when LP contract is initialised.
event InitLiquidityLauncher(address indexed token1, address indexed token2, address factory, address sender);
/// @notice Emitted when LP is launched.
event LiquidityAdded(uint256 liquidity);
/// @notice Emitted when wallet is updated.
event WalletUpdated(address indexed wallet);
/// @notice Emitted when launcher is cancelled.
event LauncherCancelled(address indexed wallet);
constructor (address _weth) public {
weth = _weth;
}
/**
* @notice Initializes main contract variables (requires launchwindow to be more than 2 days.)
* @param _market Auction address for launcher.
* @param _factory Uniswap V2 factory address.
* @param _admin Contract owner address.
* @param _wallet Withdraw wallet address.
* @param _liquidityPercent Percentage of payment currency sent to liquidity pool.
* @param _locktime How long the liquidity will be locked. Number of seconds.
*/
function initAuctionLauncher(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
)
public
{
require(_locktime < 10000000000, 'PostAuction: Enter an unix timestamp in seconds, not miliseconds');
require(_liquidityPercent <= LIQUIDITY_PRECISION, 'PostAuction: Liquidity percentage greater than 100.00% (>10000)');
require(_liquidityPercent > 0, 'PostAuction: Liquidity percentage equals zero');
require(_admin != address(0), "PostAuction: admin is the zero address");
require(_wallet != address(0), "PostAuction: wallet is the zero address");
initAccessControls(_admin);
market = IMisoAuction(_market);
token1 = IERC20(market.paymentCurrency());
token2 = IERC20(market.auctionToken());
if (address(token1) == ETH_ADDRESS) {
token1 = IERC20(weth);
}
uint256 d1 = uint256(token1.decimals());
uint256 d2 = uint256(token2.decimals());
require(d2 >= d1);
factory = IUniswapV2Factory(_factory);
bytes32 pairCodeHash = IUniswapV2Factory(_factory).pairCodeHash();
tokenPair = UniswapV2Library.pairFor(_factory, address(token1), address(token2), pairCodeHash);
wallet = _wallet;
launcherInfo.liquidityPercent = BoringMath.to16(_liquidityPercent);
launcherInfo.locktime = BoringMath.to32(_locktime);
uint256 initalTokenAmount = market.getTotalTokens().mul(_liquidityPercent).div(LIQUIDITY_PRECISION);
_safeTransferFrom(address(token2), msg.sender, initalTokenAmount);
emit InitLiquidityLauncher(address(token1), address(token2), address(_factory), _admin);
}
receive() external payable {
if(msg.sender != weth ){
depositETH();
}
}
/// @notice Deposits ETH to the contract.
function depositETH() public payable {
require(address(token1) == weth || address(token2) == weth, "PostAuction: Launcher not accepting ETH");
if (msg.value > 0 ) {
IWETH(weth).deposit{value : msg.value}();
}
}
/**
* @notice Deposits first Token to the contract.
* @param _amount Number of tokens to deposit.
*/
function depositToken1(uint256 _amount) external returns (bool success) {
return _deposit( address(token1), msg.sender, _amount);
}
/**
* @notice Deposits second Token to the contract.
* @param _amount Number of tokens to deposit.
*/
function depositToken2(uint256 _amount) external returns (bool success) {
return _deposit( address(token2), msg.sender, _amount);
}
/**
* @notice Deposits Tokens to the contract.
* @param _amount Number of tokens to deposit.
* @param _from Where the tokens to deposit will come from.
* @param _token Token address.
*/
function _deposit(address _token, address _from, uint _amount) internal returns (bool success) {
require(!launcherInfo.launched, "PostAuction: Must first launch liquidity");
require(launcherInfo.liquidityAdded == 0, "PostAuction: Liquidity already added");
require(_amount > 0, "PostAuction: Token amount must be greater than 0");
_safeTransferFrom(_token, _from, _amount);
return true;
}
/**
* @notice Checks if market wallet is set to this launcher
*/
function marketConnected() public view returns (bool) {
return market.wallet() == address(this);
}
/**
* @notice Finalizes Token sale and launches LP.
* @return liquidity Number of LPs.
*/
function finalize() external nonReentrant returns (uint256 liquidity) {
// GP: Can we remove admin, let anyone can finalise and launch?
// require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(marketConnected(), "PostAuction: Auction must have this launcher address set as the destination wallet");
require(!launcherInfo.launched);
if (!market.finalized()) {
market.finalize();
}
require(market.finalized());
launcherInfo.launched = true;
if (!market.auctionSuccessful() ) {
return 0;
}
/// @dev if the auction is settled in weth, wrap any contract balance
uint256 launcherBalance = address(this).balance;
if (launcherBalance > 0 ) {
IWETH(weth).deposit{value : launcherBalance}();
}
(uint256 token1Amount, uint256 token2Amount) = getTokenAmounts();
/// @dev cannot start a liquidity pool with no tokens on either side
if (token1Amount == 0 || token2Amount == 0 ) {
return 0;
}
address pair = factory.getPair(address(token1), address(token2));
if(pair == address(0)) {
createPool();
}
/// @dev add liquidity to pool via the pair directly
_safeTransfer(address(token1), tokenPair, token1Amount);
_safeTransfer(address(token2), tokenPair, token2Amount);
liquidity = IUniswapV2Pair(tokenPair).mint(address(this));
launcherInfo.liquidityAdded = BoringMath.to128(uint256(launcherInfo.liquidityAdded).add(liquidity));
/// @dev if unlock time not yet set, add it.
if (launcherInfo.unlock == 0 ) {
launcherInfo.unlock = BoringMath.to64(block.timestamp + uint256(launcherInfo.locktime));
}
emit LiquidityAdded(liquidity);
}
function getTokenAmounts() public view returns (uint256 token1Amount, uint256 token2Amount) {
token1Amount = getToken1Balance().mul(uint256(launcherInfo.liquidityPercent)).div(LIQUIDITY_PRECISION);
token2Amount = getToken2Balance();
uint256 tokenPrice = market.tokenPrice();
uint256 d2 = uint256(token2.decimals());
uint256 maxToken1Amount = token2Amount.mul(tokenPrice).div(10**(d2));
uint256 maxToken2Amount = token1Amount
.mul(10**(d2))
.div(tokenPrice);
/// @dev if more than the max.
if (token2Amount > maxToken2Amount) {
token2Amount = maxToken2Amount;
}
/// @dev if more than the max.
if (token1Amount > maxToken1Amount) {
token1Amount = maxToken1Amount;
}
}
/**
* @notice Withdraws LPs from the contract.
* @return liquidity Number of LPs.
*/
function withdrawLPTokens() external returns (uint256 liquidity) {
require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(launcherInfo.launched, "PostAuction: Must first launch liquidity");
require(block.timestamp >= uint256(launcherInfo.unlock), "PostAuction: Liquidity is locked");
liquidity = IERC20(tokenPair).balanceOf(address(this));
require(liquidity > 0, "PostAuction: Liquidity must be greater than 0");
_safeTransfer(tokenPair, wallet, liquidity);
}
/// @notice Withraws deposited tokens and ETH from the contract to wallet.
function withdrawDeposits() external {
require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PostAuction: Sender must be operator");
require(launcherInfo.launched, "PostAuction: Must first launch liquidity");
uint256 token1Amount = getToken1Balance();
if (token1Amount > 0 ) {
_safeTransfer(address(token1), wallet, token1Amount);
}
uint256 token2Amount = getToken2Balance();
if (token2Amount > 0 ) {
_safeTransfer(address(token2), wallet, token2Amount);
}
}
// TODO
// GP: Sweep non relevant ERC20s / ETH
//--------------------------------------------------------
// Setter functions
//--------------------------------------------------------
/**
* @notice Admin can set the wallet through this function.
* @param _wallet Wallet is where funds will be sent.
*/
function setWallet(address payable _wallet) external {
require(hasAdminRole(msg.sender));
require(_wallet != address(0), "Wallet is the zero address");
wallet = _wallet;
emit WalletUpdated(_wallet);
}
function cancelLauncher() external {
require(hasAdminRole(msg.sender));
require(!launcherInfo.launched);
launcherInfo.launched = true;
emit LauncherCancelled(msg.sender);
}
//--------------------------------------------------------
// Helper functions
//--------------------------------------------------------
/**
* @notice Creates new SLP pair through SushiSwap.
*/
function createPool() public {
factory.createPair(address(token1), address(token2));
}
//--------------------------------------------------------
// Getter functions
//--------------------------------------------------------
/**
* @notice Gets the number of first token deposited into this contract.
* @return uint256 Number of WETH.
*/
function getToken1Balance() public view returns (uint256) {
return token1.balanceOf(address(this));
}
/**
* @notice Gets the number of second token deposited into this contract.
* @return uint256 Number of WETH.
*/
function getToken2Balance() public view returns (uint256) {
return token2.balanceOf(address(this));
}
/**
* @notice Returns LP token address..
* @return address LP address.
*/
function getLPTokenAddress() public view returns (address) {
return tokenPair;
}
/**
* @notice Returns LP Token balance.
* @return uint256 LP Token balance.
*/
function getLPBalance() public view returns (uint256) {
return IERC20(tokenPair).balanceOf(address(this));
}
//--------------------------------------------------------
// Init functions
//--------------------------------------------------------
/**
* @notice Decodes and hands auction data to the initAuction function.
* @param _data Encoded data for initialization.
*/
function init(bytes calldata _data) external payable {
}
function initLauncher(
bytes calldata _data
) public {
(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
) = abi.decode(_data, (
address,
address,
address,
address,
uint256,
uint256
));
initAuctionLauncher( _market, _factory,_admin,_wallet,_liquidityPercent,_locktime);
}
/**
* @notice Collects data to initialize the auction and encodes them.
* @param _market Auction address for launcher.
* @param _factory Uniswap V2 factory address.
* @param _admin Contract owner address.
* @param _wallet Withdraw wallet address.
* @param _liquidityPercent Percentage of payment currency sent to liquidity pool.
* @param _locktime How long the liquidity will be locked. Number of seconds.
* @return _data All the data in bytes format.
*/
function getLauncherInitData(
address _market,
address _factory,
address _admin,
address _wallet,
uint256 _liquidityPercent,
uint256 _locktime
)
external
pure
returns (bytes memory _data)
{
return abi.encode(_market,
_factory,
_admin,
_wallet,
_liquidityPercent,
_locktime
);
}
} | 3,728 | 463 | 1 | 1. [H-01] PostAuctionLauncher.sol#finalize() Adding liquidity to an existing pool may allows the attacker to steal most of the tokens.
PostAuctionLauncher.finalize() can be called by anyone, and it sends tokens directly to the pair pool to mint liquidity, even when the pair pool exists.
(Access control) | 1 |
39_VaultTracker.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
import "./Abstracts.sol";
contract VaultTracker {
struct Vault {
uint256 notional;
uint256 redeemable;
uint256 exchangeRate;
}
mapping(address => Vault) public vaults;
address public immutable admin;
address public immutable cTokenAddr;
address public immutable swivel;
bool public matured;
uint256 public immutable maturity;
uint256 public maturityRate;
/// @param m Maturity timestamp of the new market
/// @param c cToken address associated with underlying for the new market
/// @param s address of the deployed swivel contract
constructor(uint256 m, address c, address s) {
admin = msg.sender;
maturity = m;
cTokenAddr = c;
swivel = s;
}
/// @notice Adds notional (nTokens) to a given user's vault
/// @param o Address that owns a vault
/// @param a Amount of notional added
function addNotional(address o, uint256 a) public onlyAdmin(admin) returns (bool) {
uint256 exchangeRate = CErc20(cTokenAddr).exchangeRateCurrent();
Vault memory vlt = vaults[o];
if (vlt.notional > 0) {
uint256 yield;
uint256 interest;
// if market has matured, calculate marginal interest between the maturity rate and previous position exchange rate
// otherwise, calculate marginal exchange rate between current and previous exchange rate.
if (matured) {
// Calculate marginal interest
yield = ((maturityRate * 1e26) / vlt.exchangeRate) - 1e26;
} else {
yield = ((exchangeRate * 1e26) / vlt.exchangeRate) - 1e26;
}
interest = (yield * vlt.notional) / 1e26;
// add interest and amount to position, reset cToken exchange rate
vlt.redeemable += interest;
vlt.notional += a;
} else {
vlt.notional = a;
}
vlt.exchangeRate = exchangeRate;
vaults[o] = vlt;
return true;
}
/// @notice Removes notional (nTokens) from a given user's vault
/// @param o Address that owns a vault
/// @param a Amount of notional to remove
function removeNotional(address o, uint256 a) public onlyAdmin(admin) returns (bool) {
Vault memory vlt = vaults[o];
require(vlt.notional >= a, "amount exceeds vault balance");
uint256 yield;
uint256 interest;
uint256 exchangeRate = CErc20(cTokenAddr).exchangeRateCurrent();
// if market has matured, calculate marginal interest between the maturity rate and previous position exchange rate
// otherwise, calculate marginal exchange rate between current and previous exchange rate.
if (matured) {
// Calculate marginal interest
yield = ((maturityRate * 1e26) / vlt.exchangeRate) - 1e26;
} else {
// calculate marginal interest
yield = ((exchangeRate * 1e26) / vlt.exchangeRate) - 1e26;
}
interest = (yield * vlt.notional) / 1e26;
// remove amount from position, Add interest to position, reset cToken exchange rate
vlt.redeemable += interest;
vlt.notional -= a;
vlt.exchangeRate = exchangeRate;
vaults[o] = vlt;
return true;
}
/// @notice Redeem's the `redeemable` + marginal interest from a given user's vault
/// @param o Address that owns a vault
function redeemInterest(address o) external onlyAdmin(admin) returns (uint256) {
Vault memory vlt = vaults[o];
uint256 redeemable = vlt.redeemable;
uint256 yield;
uint256 interest;
uint256 exchangeRate = CErc20(cTokenAddr).exchangeRateCurrent();
// if market has matured, calculate marginal interest between the maturity rate and previous position exchange rate
// otherwise, calculate marginal exchange rate between current and previous exchange rate.
if (matured) {
// Calculate marginal interest
yield = ((maturityRate * 1e26) / vlt.exchangeRate) - 1e26;
} else {
// calculate marginal interest
yield = ((exchangeRate * 1e26) / vlt.exchangeRate) - 1e26;
}
interest = (yield * vlt.notional) / 1e26;
vlt.exchangeRate = exchangeRate;
vlt.redeemable = 0;
vaults[o] = vlt;
// return adds marginal interest to previously accrued redeemable interest
return (redeemable + interest);
}
/// @notice Matures the vault and sets the market's maturityRate
function matureVault() external onlyAdmin(admin) returns (bool) {
require(!matured, 'already matured');
require(block.timestamp >= maturity, 'maturity has not been reached');
matured = true;
maturityRate = CErc20(cTokenAddr).exchangeRateCurrent();
return true;
}
/// @notice Transfers notional (nTokens) from one user to another
/// @param f Owner of the amount
/// @param t Recipient of the amount
/// @param a Amount to transfer
function transferNotionalFrom(address f, address t, uint256 a) external onlyAdmin(admin) returns (bool) {
Vault memory from = vaults[f];
Vault memory to = vaults[t];
require(from.notional >= a, "amount exceeds available balance");
uint256 yield;
uint256 interest;
uint256 exchangeRate = CErc20(cTokenAddr).exchangeRateCurrent();
// if market has matured, calculate marginal interest between the maturity rate and previous position exchange rate
// otherwise, calculate marginal exchange rate between current and previous exchange rate.
if (matured) {
// calculate marginal interest
yield = ((maturityRate * 1e26) / from.exchangeRate) - 1e26;
} else {
yield = ((exchangeRate * 1e26) / from.exchangeRate) - 1e26;
}
interest = (yield * from.notional) / 1e26;
// remove amount from position, Add interest to position, reset cToken exchange rate
from.redeemable += interest;
from.notional -= a;
from.exchangeRate = exchangeRate;
vaults[f] = from;
// transfer notional to address "t", calculate interest if necessary
if (to.notional > 0) {
uint256 newVaultInterest;
// if market has matured, calculate marginal interest between the maturity rate and previous position exchange rate
// otherwise, calculate marginal exchange rate between current and previous exchange rate.
if (matured) {
// calculate marginal interest
yield = ((maturityRate * 1e26) / to.exchangeRate) - 1e26;
} else {
yield = ((exchangeRate * 1e26) / to.exchangeRate) - 1e26;
}
newVaultInterest = (yield * to.notional) / 1e26;
// add interest and amount to position, reset cToken exchange rate
to.redeemable += newVaultInterest;
to.notional += a;
} else {
to.notional += a;
}
to.exchangeRate = exchangeRate;
vaults[t] = to;
return true;
}
/// @notice transfers, in notional, a fee payment to the Swivel contract without recalculating marginal interest for the owner
/// @param f Owner of the amount
/// @param a Amount to transfer
function transferNotionalFee(address f, uint256 a) external onlyAdmin(admin) returns(bool) {
Vault memory oVault = vaults[f];
Vault memory sVault = vaults[swivel];
// remove notional from its owner
oVault.notional -= a;
uint256 exchangeRate = CErc20(cTokenAddr).exchangeRateCurrent();
uint256 yield;
uint256 interest;
// check if exchangeRate has been stored already this block. If not, calculate marginal interest + store exchangeRate
if (sVault.exchangeRate != exchangeRate) {
// the rate will be 0 if swivel did not already have a vault
if (sVault.exchangeRate != 0) {
// if market has matured, calculate marginal interest between the maturity rate and previous position exchange rate
// otherwise, calculate marginal exchange rate between current and previous exchange rate.
if (matured) {
// calculate marginal interest
yield = ((maturityRate * 1e26) / sVault.exchangeRate) - 1e26;
} else {
yield = ((exchangeRate * 1e26) / sVault.exchangeRate) - 1e26;
}
interest = (yield * sVault.notional) / 1e26;
// add interest and amount, reset cToken exchange rate
sVault.redeemable += interest;
}
sVault.exchangeRate = exchangeRate;
}
// add notional to swivel's vault
sVault.notional += a;
// store the adjusted vaults
vaults[swivel] = sVault;
vaults[f] = oVault;
return true;
}
/// @notice Returns both relevant balances for a given user's vault
/// @param o Address that owns a vault
function balancesOf(address o) public view returns (uint256, uint256) {
return (vaults[o].notional, vaults[o].redeemable);
}
modifier onlyAdmin(address a) {
require(msg.sender == a, 'sender must be admin');
_;
}
} | 2,192 | 255 | 1 | 1. [H-03] transferNotionalFrom doesn't check `from != to`. (Lack of input validation, Unchecked addresses)
The function `transferNotionalFrom` of VaultTracker.sol uses temporary variables to store the balances. If the "from" and "to" address are the same then the balance of "from" is overwritten by the balance of "to". This means the balance of "from" and "to" are increased and no balances are decreased, effectively printing money.
2. [M-01] Admin is a single-point of failure without any mitigations. (Lack of Access control, Centralization risks)
Admin role has absolute power across Swivel, Marketplace and VaultTracker contracts with several onlyOwner functions.
3. [M-02] Missing event & timelock for critical onlyAdmin functions. (Timestamp manipulation)
onlyAdmin functions that change critical contract parameters/addresses/state should emit events and consider adding timelocks so that users and other privileged roles can detect upcoming changes (by offchain monitoring of events) and have the time to react to them.
| 3 |
104_CoreCollection.sol | //SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {ERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {ERC721Payable} from "./ERC721Payable.sol";
import {ERC721Claimable} from "./ERC721Claimable.sol";
import {IRoyaltyVault} from "@chestrnft/royalty-vault/interfaces/IRoyaltyVault.sol";
contract CoreCollection is
Ownable,
ERC721Claimable,
ERC721Enumerable,
ERC721Payable
{
bool public initialized;
string private _name;
string private _symbol;
string private _baseUri;
uint256 public maxSupply;
uint256 public startingIndex;
uint256 public startingIndexBlock;
string public HASHED_PROOF = "";
event ClaimInitialized(bytes32 root);
event NewCollectionMeta(string name, string symbol);
event NewClaim(address claimedBy, address to, uint256 tokenId);
event StartingIndexSet(uint256 index);
event RoyaltyVaultInitialized(address royaltyVault);
event NewHashedProof(string proof);
event NewWithdrawal(address to, uint256 amount);
constructor() ERC721("", "") {}
// ----------------- MODIFIER -----------------
modifier onlyInitialized() {
require(initialized, "CoreCollection: Not initialized");
_;
}
modifier onlyUnInitialized() {
require(!initialized, "CoreCollection: Already initialized");
_;
}
modifier onlyValidSupply(uint256 _maxSupply) {
require(
_maxSupply > 0,
"CoreCollection: Max supply should be greater than 0"
);
_;
}
modifier tokenExists(uint256 _tokenId) {
require(_exists(_tokenId), "CoreCollection: Invalid token id");
_;
}
// ----------------- EXTERNAL -----------------
/**
* @notice Initializes the collection
* @dev This method is being called from the CoreFactory contract
* @param _collectionName Name of the collection
* @param _collectionSymbol Symbol of the collection
* @param _collectionURI Base URI for the collection
* @param _maxSupply The maximum number of tokens that can be minted
* @param _mintFee The price of a token in this collection
* @param _payableToken The address of the ERC20 this collection uses to settle transactions
* @param _isForSale Whether or not tokens from this collection can be purchased. If false, tokens can only be claimed
* @param _splitFactory base URI for the collection
*/
function initialize(
string memory _collectionName,
string memory _collectionSymbol,
string memory _collectionURI,
uint256 _maxSupply,
uint256 _mintFee,
address _payableToken,
bool _isForSale,
address _splitFactory
) external onlyOwner onlyValidSupply(_maxSupply) {
_name = _collectionName;
_symbol = _collectionSymbol;
_baseUri = _collectionURI;
maxSupply = _maxSupply;
mintFee = _mintFee;
payableToken = IERC20(_payableToken);
isForSale = _isForSale;
splitFactory = _splitFactory;
initialized = true;
}
/**
* @notice Allows the collection owner to airdrop tokens
* @dev The Merkle tree defines for each address how much token can be claimed
* @dev This method can only be called once
* @param _root A Merkle root
*/
function initializeClaims(bytes32 _root)
external
onlyOwner
onlyNotClaimableSet
onlyValidRoot(_root)
{
_setMerkelRoot(_root);
emit ClaimInitialized(_root);
}
/**
* @notice Allows the collection owner to change the collection's name and symbol
* @dev This function is only callable by the collection's owner
* @param _collectionName A collection name
* @param _collectionSymbol A collection symbol
*/
function setCollectionMeta(
string memory _collectionName,
string memory _collectionSymbol
) external onlyOwner {
_name = _collectionName;
_symbol = _collectionSymbol;
emit NewCollectionMeta(_collectionName, _collectionSymbol);
}
/**
* @notice This function is called to mint tokens from this ERC721 collection
* @dev The collection must be initialized first
* @param to Token recipient
* @param isClaim Whether the user want claim a token that has been airdropped to him or want to purchase the token
* @param claimableAmount The amount of tokens the user has been airdropped
* @param amount The amount of tokens the user wants to mint
* @param merkleProof A merkle proof. Needed to verify if the user can claim a token
*/
function mintToken(
address to,
bool isClaim,
uint256 claimableAmount,
uint256 amount,
bytes32[] calldata merkleProof
) external onlyInitialized {
require(amount > 0, "CoreCollection: Amount should be greater than 0");
require(
totalSupply() + amount <= maxSupply,
"CoreCollection: Over Max Supply"
);
if (isClaim) {
require(claimableSet(), "CoreCollection: No claimable");
require(
canClaim(msg.sender, claimableAmount, amount, merkleProof),
"CoreCollection: Can't claim"
);
_claim(msg.sender, amount);
} else {
require(isForSale, "CoreCollection: Not for sale");
if (mintFee > 0) {
_handlePayment(mintFee * amount);
}
}
batchMint(to, amount, isClaim);
}
/**
* @notice Allows the contract owner to withdraw the funds generated by the token sales
* @dev If a royalty vault isn't set, tokens are kept within this contract and can be withdrawn by the token owner
*/
function withdraw() external onlyOwner {
uint256 amount = payableToken.balanceOf(address(this));
payableToken.transferFrom(address(this), msg.sender, amount);
emit NewWithdrawal(msg.sender, amount);
}
/**
* @notice Set royalty vault address for collection
* @dev All revenue (Primary sales + royalties from secondardy sales)
* from the collection are transferred to the vault when the vault is initialized
* @param _royaltyVault The address of the royalty vault
*/
function setRoyaltyVault(address _royaltyVault)
external
onlyVaultUninitialized
{
require(
msg.sender == splitFactory || msg.sender == owner(),
"CoreCollection: Only Split Factory or owner can initialize vault."
);
royaltyVault = _royaltyVault;
emit RoyaltyVaultInitialized(_royaltyVault);
}
/**
* @notice Set a provenance hash
* @dev This hash is used to verify the minting ordering of a collection (à la BAYC)
* This hash is generated off-chain
* @param _proof The SHA256 generated hash
*/
function setHashedProof(string calldata _proof) external onlyOwner {
require(
bytes(HASHED_PROOF).length == 0,
"CoreCollection: Hashed Proof is set"
);
HASHED_PROOF = _proof;
emit NewHashedProof(_proof);
}
// ----------------- PUBLIC -----------------
/**
* @notice Set the mint starting index
* @dev The starting index can only be generated once
*/
function setStartingIndex() public {
require(
startingIndex == 0,
"CoreCollection: Starting index is already set"
);
startingIndex =
(uint256(
keccak256(abi.encodePacked("CoreCollection", block.number))
) % maxSupply) +
1;
startingIndexBlock = uint256(block.number);
emit StartingIndexSet(startingIndex);
}
// ---------------- VIEW ----------------
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function baseURI() public view returns (string memory) {
return _baseUri;
}
function _baseURI() internal view override returns (string memory) {
return _baseUri;
}
// ---------------- PRIVATE ----------------
/**
* @notice Mint token
* @dev A starting index is calculated at the time of first mint
* returns a tokenId
* @param _to Token recipient
*/
function mint(address _to) private returns (uint256 tokenId) {
if (startingIndex == 0) {
setStartingIndex();
}
tokenId = ((startingIndex + totalSupply()) % maxSupply) + 1;
_mint(_to, tokenId);
}
/**
* @notice Mint tokens in batch
* @param _to Token recipient
* @param _amount Number of tokens to include in batch
* @param _isClaim Whether the batch mint is an airdrop or not
*/
function batchMint(
address _to,
uint256 _amount,
bool _isClaim
) private {
for (uint256 i = 0; i < _amount; i++) {
uint256 tokenId = mint(_to);
if (_isClaim) {
emit NewClaim(msg.sender, _to, tokenId);
}
}
}
// ---------------- INTERNAL ----------------
/**
* @notice This hook transfers tokens sitting in the royalty vault to the split contract
* @dev The split contract is a contract that allows a team to share revenue together
* @param _from Transfer sender
* @param _to Transfer recipient
* @param _tokenId TokenId of token being transferred
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _tokenId);
if (
royaltyVault != address(0) &&
IRoyaltyVault(royaltyVault).getVaultBalance() > 0
) {
IRoyaltyVault(royaltyVault).sendToSplitter();
}
}
} | 2,331 | 311 | 3 | 1. [H-04] CoreCollection can be reinitialized. (Initialization)
Reinitialization is possible for CoreCollection as `initialize` function sets `initialized` flag, but doesn't control for it, so the function can be rerun multiple times.
2. [H-07] Duplicate NFTs Can Be Minted if payableToken Has a Callback Attached to it. (Reentrancy)
However, because the payableToken is paid before a token is minted, it may be possible to reenter the `mintToken()` function if there is a callback attached before or after the token transfer.
3. [H-08] Funds cannot be withdrawn in CoreCollection.withdraw. (Unchecked external calls)
The `CoreCollection.withdraw` function uses payableToken.transferFrom(address(this), msg.sender, amount) to transfer tokens from the CoreCollection contract to the msg.sender ( who is the owner of the contract).
4. [M-03] RoyaltyVault.sol is Not Equipped to Handle On-Chain Royalties From Secondary Sales
5. [M-05] Gas costs will likely result in any fees sent to the Splitter being economically unviable to recover (Gas limit)
Function `mintToken` and `_beforeTokenTransfer`
6. [M-06] CoreCollection's token transfer can be disabled
`_beforeTokenTransfer` runs IRoyaltyVault(royaltyVault).sendToSplitter() whenever royaltyVault is set and have positive balance:
7. [M-11] Not handling return value of transferFrom command can create inconsistency. (Inconsistency)
Function `withdraw` same as [H-08]
8. [M-12] `CoreCollection.setRoyaltyVault` doesn't check royaltyVault.royaltyAsset against payableToken, resulting in potential permanent lock of payableTokens in royaltyVault | 8 |
12_Cauldron.sol | // SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import "./interfaces/vault/IFYToken.sol";
import "./interfaces/vault/IOracle.sol";
import "./interfaces/vault/DataTypes.sol";
import "./utils/access/AccessControl.sol";
import "./math/WMul.sol";
import "./math/WDiv.sol";
import "./math/CastU128I128.sol";
import "./math/CastI128U128.sol";
import "./math/CastU256U32.sol";
import "./math/CastU256I256.sol";
library CauldronMath {
/// @dev Add a number (which might be negative) to a positive, and revert if the result is negative.
function add(uint128 x, int128 y) internal pure returns (uint128 z) {
require (y > 0 || x >= uint128(-y), "Result below zero");
z = y > 0 ? x + uint128(y) : x - uint128(-y);
}
}
contract Cauldron is AccessControl() {
using CauldronMath for uint128;
using WMul for uint256;
using WDiv for uint256;
using CastU128I128 for uint128;
using CastU256U32 for uint256;
using CastU256I256 for uint256;
using CastI128U128 for int128;
event AuctionIntervalSet(uint32 indexed auctionInterval);
event AssetAdded(bytes6 indexed assetId, address indexed asset);
event SeriesAdded(bytes6 indexed seriesId, bytes6 indexed baseId, address indexed fyToken);
event IlkAdded(bytes6 indexed seriesId, bytes6 indexed ilkId);
event SpotOracleAdded(bytes6 indexed baseId, bytes6 indexed ilkId, address indexed oracle, uint32 ratio);
event RateOracleAdded(bytes6 indexed baseId, address indexed oracle);
event DebtLimitsSet(bytes6 indexed baseId, bytes6 indexed ilkId, uint96 max, uint24 min, uint8 dec);
event VaultBuilt(bytes12 indexed vaultId, address indexed owner, bytes6 indexed seriesId, bytes6 ilkId);
event VaultTweaked(bytes12 indexed vaultId, bytes6 indexed seriesId, bytes6 indexed ilkId);
event VaultDestroyed(bytes12 indexed vaultId);
event VaultGiven(bytes12 indexed vaultId, address indexed receiver);
event VaultPoured(bytes12 indexed vaultId, bytes6 indexed seriesId, bytes6 indexed ilkId, int128 ink, int128 art);
event VaultStirred(bytes12 indexed from, bytes12 indexed to, uint128 ink, uint128 art);
event VaultRolled(bytes12 indexed vaultId, bytes6 indexed seriesId, uint128 art);
event VaultLocked(bytes12 indexed vaultId, uint256 indexed timestamp);
event SeriesMatured(bytes6 indexed seriesId, uint256 rateAtMaturity);
// ==== Configuration data ====
mapping (bytes6 => address) public assets;
mapping (bytes6 => DataTypes.Series) public series;
mapping (bytes6 => mapping(bytes6 => bool)) public ilks;
mapping (bytes6 => IOracle) public rateOracles;
mapping (bytes6 => mapping(bytes6 => DataTypes.SpotOracle)) public spotOracles;
// ==== Protocol data ====
mapping (bytes6 => mapping(bytes6 => DataTypes.Debt)) public debt;
mapping (bytes6 => uint256) public ratesAtMaturity;
uint32 public auctionInterval;
// ==== User data ====
mapping (bytes12 => DataTypes.Vault) public vaults;
mapping (bytes12 => DataTypes.Balances) public balances;
mapping (bytes12 => uint32) public auctions;
// ==== Administration ====
/// @dev Add a new Asset.
function addAsset(bytes6 assetId, address asset)
external
auth
{
require (assetId != bytes6(0), "Asset id is zero");
require (assets[assetId] == address(0), "Id already used");
assets[assetId] = asset;
emit AssetAdded(assetId, address(asset));
}
/// @dev Set the maximum and minimum debt for an underlying and ilk pair. Can be reset.
function setDebtLimits(bytes6 baseId, bytes6 ilkId, uint96 max, uint24 min, uint8 dec)
external
auth
{
require (assets[baseId] != address(0), "Base not found");
require (assets[ilkId] != address(0), "Ilk not found");
DataTypes.Debt memory debt_ = debt[baseId][ilkId];
debt_.max = max;
debt_.min = min;
debt_.dec = dec;
debt[baseId][ilkId] = debt_;
emit DebtLimitsSet(baseId, ilkId, max, min, dec);
}
/// @dev Set a rate oracle. Can be reset.
function setRateOracle(bytes6 baseId, IOracle oracle)
external
auth
{
require (assets[baseId] != address(0), "Base not found");
rateOracles[baseId] = oracle;
emit RateOracleAdded(baseId, address(oracle));
}
/// @dev Set the interval for which vaults being auctioned can't be grabbed by another liquidation engine
function setAuctionInterval(uint32 auctionInterval_)
external
auth
{
auctionInterval = auctionInterval_;
emit AuctionIntervalSet(auctionInterval_);
}
/// @dev Set a spot oracle and its collateralization ratio. Can be reset.
function setSpotOracle(bytes6 baseId, bytes6 ilkId, IOracle oracle, uint32 ratio)
external
auth
{
require (assets[baseId] != address(0), "Base not found");
require (assets[ilkId] != address(0), "Ilk not found");
spotOracles[baseId][ilkId] = DataTypes.SpotOracle({
oracle: oracle,
ratio: ratio
});
emit SpotOracleAdded(baseId, ilkId, address(oracle), ratio);
}
/// @dev Add a new series
function addSeries(bytes6 seriesId, bytes6 baseId, IFYToken fyToken)
external
auth
{
require (seriesId != bytes6(0), "Series id is zero");
address base = assets[baseId];
require (base != address(0), "Base not found");
require (fyToken != IFYToken(address(0)), "Series need a fyToken");
require (fyToken.underlying() == base, "Mismatched series and base");
require (rateOracles[baseId] != IOracle(address(0)), "Rate oracle not found");
require (series[seriesId].fyToken == IFYToken(address(0)), "Id already used");
series[seriesId] = DataTypes.Series({
fyToken: fyToken,
maturity: fyToken.maturity().u32(),
baseId: baseId
});
emit SeriesAdded(seriesId, baseId, address(fyToken));
}
/// @dev Add a new Ilk (approve an asset as collateral for a series).
function addIlks(bytes6 seriesId, bytes6[] calldata ilkIds)
external
auth
{
DataTypes.Series memory series_ = series[seriesId];
require (
series_.fyToken != IFYToken(address(0)),
"Series not found"
);
for (uint256 i = 0; i < ilkIds.length; i++) {
require (
spotOracles[series_.baseId][ilkIds[i]].oracle != IOracle(address(0)),
"Spot oracle not found"
);
ilks[seriesId][ilkIds[i]] = true;
emit IlkAdded(seriesId, ilkIds[i]);
}
}
// ==== Vault management ====
/// @dev Create a new vault, linked to a series (and therefore underlying) and a collateral
function build(address owner, bytes12 vaultId, bytes6 seriesId, bytes6 ilkId)
external
auth
returns(DataTypes.Vault memory vault)
{
require (vaultId != bytes12(0), "Vault id is zero");
require (vaults[vaultId].seriesId == bytes6(0), "Vault already exists");
require (ilks[seriesId][ilkId] == true, "Ilk not added to series");
vault = DataTypes.Vault({
owner: owner,
seriesId: seriesId,
ilkId: ilkId
});
vaults[vaultId] = vault;
emit VaultBuilt(vaultId, owner, seriesId, ilkId);
}
/// @dev Destroy an empty vault. Used to recover gas costs.
function destroy(bytes12 vaultId)
external
auth
{
DataTypes.Balances memory balances_ = balances[vaultId];
require (balances_.art == 0 && balances_.ink == 0, "Only empty vaults");
delete auctions[vaultId];
delete vaults[vaultId];
emit VaultDestroyed(vaultId);
}
/// @dev Change a vault series and/or collateral types.
function _tweak(bytes12 vaultId, DataTypes.Vault memory vault)
internal
{
require (ilks[vault.seriesId][vault.ilkId] == true, "Ilk not added to series");
vaults[vaultId] = vault;
emit VaultTweaked(vaultId, vault.seriesId, vault.ilkId);
}
/// @dev Change a vault series and/or collateral types.
/// We can change the series if there is no debt, or assets if there are no assets
function tweak(bytes12 vaultId, bytes6 seriesId, bytes6 ilkId)
external
auth
returns(DataTypes.Vault memory vault)
{
DataTypes.Balances memory balances_ = balances[vaultId];
vault = vaults[vaultId];
if (seriesId != vault.seriesId) {
require (balances_.art == 0, "Only with no debt");
vault.seriesId = seriesId;
}
if (ilkId != vault.ilkId) {
require (balances_.ink == 0, "Only with no collateral");
vault.ilkId = ilkId;
}
_tweak(vaultId, vault);
}
/// @dev Transfer a vault to another user.
function _give(bytes12 vaultId, address receiver)
internal
returns(DataTypes.Vault memory vault)
{
vault = vaults[vaultId];
vault.owner = receiver;
vaults[vaultId] = vault;
emit VaultGiven(vaultId, receiver);
}
/// @dev Transfer a vault to another user.
function give(bytes12 vaultId, address receiver)
external
auth
returns(DataTypes.Vault memory vault)
{
vault = _give(vaultId, receiver);
}
// ==== Asset and debt management ====
function vaultData(bytes12 vaultId, bool getSeries)
internal
view
returns (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_)
{
vault_ = vaults[vaultId];
require (vault_.seriesId != bytes6(0), "Vault not found");
if (getSeries) series_ = series[vault_.seriesId];
balances_ = balances[vaultId];
}
/// @dev Move collateral and debt between vaults.
function stir(bytes12 from, bytes12 to, uint128 ink, uint128 art)
external
auth
returns (DataTypes.Balances memory, DataTypes.Balances memory)
{
(DataTypes.Vault memory vaultFrom, , DataTypes.Balances memory balancesFrom) = vaultData(from, false);
(DataTypes.Vault memory vaultTo, , DataTypes.Balances memory balancesTo) = vaultData(to, false);
if (ink > 0) {
require (vaultFrom.ilkId == vaultTo.ilkId, "Different collateral");
balancesFrom.ink -= ink;
balancesTo.ink += ink;
}
if (art > 0) {
require (vaultFrom.seriesId == vaultTo.seriesId, "Different series");
balancesFrom.art -= art;
balancesTo.art += art;
}
balances[from] = balancesFrom;
balances[to] = balancesTo;
if (ink > 0) require(_level(vaultFrom, balancesFrom, series[vaultFrom.seriesId]) >= 0, "Undercollateralized at origin");
if (art > 0) require(_level(vaultTo, balancesTo, series[vaultTo.seriesId]) >= 0, "Undercollateralized at destination");
emit VaultStirred(from, to, ink, art);
return (balancesFrom, balancesTo);
}
/// @dev Add collateral and borrow from vault, pull assets from and push borrowed asset to user
/// Or, repay to vault and remove collateral, pull borrowed asset from and push assets to user
function _pour(
bytes12 vaultId,
DataTypes.Vault memory vault_,
DataTypes.Balances memory balances_,
DataTypes.Series memory series_,
int128 ink,
int128 art
)
internal returns (DataTypes.Balances memory)
{
// For now, the collateralization checks are done outside to allow for underwater operation. That might change.
if (ink != 0) {
balances_.ink = balances_.ink.add(ink);
}
// Modify vault and global debt records. If debt increases, check global limit.
if (art != 0) {
DataTypes.Debt memory debt_ = debt[series_.baseId][vault_.ilkId];
balances_.art = balances_.art.add(art);
debt_.sum = debt_.sum.add(art);
uint128 dust = debt_.min * uint128(10) ** debt_.dec;
uint128 line = debt_.max * uint128(10) ** debt_.dec;
require (balances_.art == 0 || balances_.art >= dust, "Min debt not reached");
if (art > 0) require (debt_.sum <= line, "Max debt exceeded");
debt[series_.baseId][vault_.ilkId] = debt_;
}
balances[vaultId] = balances_;
emit VaultPoured(vaultId, vault_.seriesId, vault_.ilkId, ink, art);
return balances_;
}
/// @dev Manipulate a vault, ensuring it is collateralized afterwards.
/// To be used by debt management contracts.
function pour(bytes12 vaultId, int128 ink, int128 art)
external
auth
returns (DataTypes.Balances memory)
{
(DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true);
balances_ = _pour(vaultId, vault_, balances_, series_, ink, art);
if (balances_.art > 0 && (ink < 0 || art > 0))
require(_level(vault_, balances_, series_) >= 0, "Undercollateralized");
return balances_;
}
/// @dev Give a non-timestamped vault to another user, and timestamp it.
/// To be used for liquidation engines.
function grab(bytes12 vaultId, address receiver)
external
auth
{
uint32 now_ = uint32(block.timestamp);
require (auctions[vaultId] + auctionInterval <= now_, "Vault under auction");
(DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true);
require(_level(vault_, balances_, series_) < 0, "Not undercollateralized");
auctions[vaultId] = now_;
_give(vaultId, receiver);
emit VaultLocked(vaultId, now_);
}
/// @dev Reduce debt and collateral from a vault, ignoring collateralization checks.
/// To be used by liquidation engines.
function slurp(bytes12 vaultId, uint128 ink, uint128 art)
external
auth
returns (DataTypes.Balances memory)
{
(DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true);
balances_ = _pour(vaultId, vault_, balances_, series_, -(ink.i128()), -(art.i128()));
return balances_;
}
/// @dev Change series and debt of a vault.
/// The module calling this function also needs to buy underlying in the pool for the new series, and sell it in pool for the old series.
function roll(bytes12 vaultId, bytes6 newSeriesId, int128 art)
external
auth
returns (DataTypes.Vault memory, DataTypes.Balances memory)
{
(DataTypes.Vault memory vault_, DataTypes.Series memory oldSeries_, DataTypes.Balances memory balances_) = vaultData(vaultId, true);
DataTypes.Series memory newSeries_ = series[newSeriesId];
require (oldSeries_.baseId == newSeries_.baseId, "Mismatched bases in series");
// Change the vault series
vault_.seriesId = newSeriesId;
_tweak(vaultId, vault_);
// Change the vault balances
balances_ = _pour(vaultId, vault_, balances_, newSeries_, 0, art);
require(_level(vault_, balances_, newSeries_) >= 0, "Undercollateralized");
emit VaultRolled(vaultId, newSeriesId, balances_.art);
return (vault_, balances_);
}
// ==== Accounting ====
/// @dev Return the collateralization level of a vault. It will be negative if undercollateralized.
function level(bytes12 vaultId) public returns (int256) {
(DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true);
return _level(vault_, balances_, series_);
}
/// @dev Record the borrowing rate at maturity for a series
function mature(bytes6 seriesId)
public
{
DataTypes.Series memory series_ = series[seriesId];
require (uint32(block.timestamp) >= series_.maturity, "Only after maturity");
require (ratesAtMaturity[seriesId] == 0, "Already matured");
_mature(seriesId, series_);
}
/// @dev Record the borrowing rate at maturity for a series
function _mature(bytes6 seriesId, DataTypes.Series memory series_)
internal
{
IOracle rateOracle = rateOracles[series_.baseId];
(uint256 rateAtMaturity,) = rateOracle.get(series_.baseId, bytes32("rate"), 1e18);
ratesAtMaturity[seriesId] = rateAtMaturity;
emit SeriesMatured(seriesId, rateAtMaturity);
}
/// @dev Retrieve the rate accrual since maturity, maturing if necessary.
function accrual(bytes6 seriesId)
public
returns (uint256)
{
DataTypes.Series memory series_ = series[seriesId];
require (uint32(block.timestamp) >= series_.maturity, "Only after maturity");
return _accrual(seriesId, series_);
}
/// @dev Retrieve the rate accrual since maturity, maturing if necessary.
/// Note: Call only after checking we are past maturity
function _accrual(bytes6 seriesId, DataTypes.Series memory series_)
private
returns (uint256 accrual_)
{
uint256 rateAtMaturity = ratesAtMaturity[seriesId];
if (rateAtMaturity == 0) {
_mature(seriesId, series_);
} else {
IOracle rateOracle = rateOracles[series_.baseId];
(uint256 rate,) = rateOracle.get(series_.baseId, bytes32("rate"), 1e18);
accrual_ = rate.wdiv(rateAtMaturity);
}
accrual_ = accrual_ >= 1e18 ? accrual_ : 1e18;
}
/// @dev Return the collateralization level of a vault. It will be negative if undercollateralized.
function _level(
DataTypes.Vault memory vault_,
DataTypes.Balances memory balances_,
DataTypes.Series memory series_
)
internal
returns (int256)
{
DataTypes.SpotOracle memory spotOracle_ = spotOracles[series_.baseId][vault_.ilkId];
uint256 ratio = uint256(spotOracle_.ratio) * 1e12;
(uint256 inkValue,) = spotOracle_.oracle.get(series_.baseId, vault_.ilkId, balances_.ink);
if (uint32(block.timestamp) >= series_.maturity) {
uint256 accrual_ = _accrual(vault_.seriesId, series_);
return inkValue.i256() - uint256(balances_.art).wmul(accrual_).wmul(ratio).i256();
}
return inkValue.i256() - uint256(balances_.art).wmul(ratio).i256();
}
} | 4,632 | 480 | 2 | 1. [M-01] Potential griefing with DoS by front-running vault creation with same `vaultID`. (DoS, Front-running)
The `vaultID` for a new vault being built is required to be specified by the user building a vault via the build() function (instead of being assigned by the Cauldron/protocol). An attacker can observe a build() as part of a batch transaction in the mempool, identify the vaultID being requested, and front-run that by constructing a malicious batch transaction with only the build operation with that same vaultID.
2. [M-03] Witch can't give back vault after 2x grab
The `grab` function stores the previous owner in vaultOwners[vaultId], and then the contract itself is the new owner (via cauldron.grab and cauldron._give). The vaultOwners[vaultId] is overwritten at the second grab
3. [M-05] Uninitialized or Incorrectly set auctionInterval may lead to liquidation engine livelock (Initialization)
The `grab()` function in Cauldron is used by the Witch or other liquidation engines to grab vaults that are under-collateralized. To prevent re-grabbing without sufficient time for auctioning collateral/debt, the logic uses an `auctionInterval` threshold to give a reasonable window to a liquidation engine that has grabbed the vault.
4. [M-08] Users can avoid paying borrowing interest after the fyToken matures (Timestamp manipulation)
In the last step, the `elapsed` time (line 61) is equal to the current timestamp since the vault is never grabbed by Witch before, and thus the auction time of the vault, `cauldron.auctions(vaultId)`, is 0 (the default mapping value). Therefore, the collateral is sold at a price of balances_.art/balances_.ink (line 74).
| 4 |
5_Vether.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
// Interfaces
import "./interfaces/iVETHER.sol";
// Token Contract
contract Vether is iVETHER {
// Coin Defaults
string public override name;
string public override symbol;
uint public override decimals = 18;
uint public override totalSupply = 1*10**6 * (10 ** decimals);
uint public totalFees;
mapping(address=>bool) public mapAddress_Excluded;
// ERC-20 Mappings
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
// Minting event
constructor() {
name = "Vether";
symbol = "VETH";
_balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function balanceOf(address account) public view override returns (uint) {
return _balances[account];
}
function allowance(address owner, address spender) public view virtual override returns (uint) {
return _allowances[owner][spender];
}
// iERC20 Transfer function
function transfer(address recipient, uint amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
// iERC20 Approve, change allowance functions
function approve(address spender, uint amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function increaseAllowance(address spender, uint addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
return true;
}
function _approve(address owner, address spender, uint amount) internal virtual {
require(owner != address(0), "iERC20: approve from the zero address");
require(spender != address(0), "iERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// iERC20 TransferFrom function
function transferFrom(address sender, address recipient, uint amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender] - amount);
return true;
}
// Internal transfer function which includes the Fee
function _transfer(address _from, address _to, uint _value) private {
require(_balances[_from] >= _value, 'Must not send more than balance');
require(_balances[_to] + _value >= _balances[_to], 'Balance overflow');
_balances[_from] -= _value;
uint _fee = _getFee(_from, _to, _value);
_balances[_to] += (_value - _fee);
_balances[address(this)] += _fee;
totalFees += _fee;
emit Transfer(_from, _to, (_value - _fee));
if (!mapAddress_Excluded[_from] && !mapAddress_Excluded[_to]) {
emit Transfer(_from, address(this), _fee);
}
}
// Calculate Fee amount
function _getFee(address _from, address _to, uint _value) private view returns (uint) {
if (mapAddress_Excluded[_from] || mapAddress_Excluded[_to]) {
return 0;
} else {
return (_value / 1000);
}
}
function addExcluded(address excluded) public {
mapAddress_Excluded[excluded] = true;
}
} | 862 | 96 | 1 | 1. [H-21] Anyone Can Avoid All Vether Transfer Fees By Adding Their Address to the Vether ExcludedAddresses List (Access control)
Vether.sol implements a fee on every token transfer, unless either the sender or the recipient exists on a list of excluded addresses (mapAddress_Excluded). However, the `addExcluded()` function in Vether.sol has no restrictions on who can call it. So any user can call addExcluded with their own address as the argument, and bypass all transfer fees. | 1 |
5_DAO.sol | // SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.3;
// Interfaces
import "./interfaces/iERC20.sol";
import "./interfaces/iUTILS.sol";
import "./interfaces/iVADER.sol";
import "./interfaces/iVAULT.sol";
import "./interfaces/iROUTER.sol";
//======================================VADER=========================================//
contract DAO {
struct GrantDetails{
address recipient;
uint amount;
}
bool private inited;
uint public proposalCount;
address public VADER;
address public USDV;
address public VAULT;
uint public coolOffPeriod;
mapping(uint => GrantDetails) public mapPID_grant;
mapping(uint => address) public mapPID_address;
mapping(uint => string) public mapPID_type;
mapping(uint => uint) public mapPID_votes;
mapping(uint => uint) public mapPID_timeStart;
mapping(uint => bool) public mapPID_finalising;
mapping(uint => bool) public mapPID_finalised;
mapping(uint => mapping(address => uint)) public mapPIDMember_votes;
event NewProposal(address indexed member, uint indexed proposalID, string proposalType);
event NewVote(address indexed member, uint indexed proposalID, uint voteWeight, uint totalVotes, string proposalType);
event ProposalFinalising(address indexed member,uint indexed proposalID, uint timeFinalised, string proposalType);
event CancelProposal(address indexed member, uint indexed oldProposalID, uint oldVotes, uint newVotes, uint totalWeight);
event FinalisedProposal(address indexed member,uint indexed proposalID, uint votesCast, uint totalWeight, string proposalType);
//=====================================CREATION=========================================//
// Constructor
constructor() {
}
function init(address _vader, address _usdv, address _vault) public {
require(inited == false);
inited = true;
VADER = _vader;
USDV = _usdv;
VAULT = _vault;
coolOffPeriod = 1;
}
//============================== CREATE PROPOSALS ================================//
// Action with funding
function newGrantProposal(address recipient, uint amount) public {
string memory typeStr = "GRANT";
proposalCount += 1;
mapPID_type[proposalCount] = typeStr;
GrantDetails memory grant;
grant.recipient = recipient;
grant.amount = amount;
mapPID_grant[proposalCount] = grant;
emit NewProposal(msg.sender, proposalCount, typeStr);
}
// Action with address parameter
function newAddressProposal(address proposedAddress, string memory typeStr) public {
proposalCount += 1;
mapPID_address[proposalCount] = proposedAddress;
mapPID_type[proposalCount] = typeStr;
emit NewProposal(msg.sender, proposalCount, typeStr);
}
//============================== VOTE && FINALISE ================================//
// Vote for a proposal
function voteProposal(uint proposalID) public returns (uint voteWeight) {
bytes memory _type = bytes(mapPID_type[proposalID]);
voteWeight = countMemberVotes(proposalID);
if(hasQuorum(proposalID) && mapPID_finalising[proposalID] == false){
if(isEqual(_type, 'DAO') || isEqual(_type, 'UTILS') || isEqual(_type, 'REWARD')){
if(hasMajority(proposalID)){
_finalise(proposalID);
}
} else {
_finalise(proposalID);
}
}
emit NewVote(msg.sender, proposalID, voteWeight, mapPID_votes[proposalID], string(_type));
}
function _finalise(uint _proposalID) internal {
bytes memory _type = bytes(mapPID_type[_proposalID]);
mapPID_finalising[_proposalID] = true;
mapPID_timeStart[_proposalID] = block.timestamp;
emit ProposalFinalising(msg.sender, _proposalID, block.timestamp+coolOffPeriod, string(_type));
}
// If an existing proposal, allow a minority to cancel
function cancelProposal(uint oldProposalID, uint newProposalID) public {
require(mapPID_finalising[oldProposalID], "Must be finalising");
require(hasMinority(newProposalID), "Must have minority");
require(isEqual(bytes(mapPID_type[oldProposalID]), bytes(mapPID_type[newProposalID])), "Must be same");
mapPID_votes[oldProposalID] = 0;
emit CancelProposal(msg.sender, oldProposalID, mapPID_votes[oldProposalID], mapPID_votes[newProposalID], iVAULT(VAULT).totalWeight());
}
// Proposal with quorum can finalise after cool off period
function finaliseProposal(uint proposalID) public {
require((block.timestamp - mapPID_timeStart[proposalID]) > coolOffPeriod, "Must be after cool off");
require(mapPID_finalising[proposalID] == true, "Must be finalising");
if(!hasQuorum(proposalID)){
_finalise(proposalID);
}
bytes memory _type = bytes(mapPID_type[proposalID]);
if (isEqual(_type, 'GRANT')){
grantFunds(proposalID);
} else if (isEqual(_type, 'UTILS')){
moveUtils(proposalID);
} else if (isEqual(_type, 'REWARD')){
moveRewardAddress(proposalID);
}
}
function completeProposal(uint _proposalID) internal {
string memory _typeStr = mapPID_type[_proposalID];
emit FinalisedProposal(msg.sender, _proposalID, mapPID_votes[_proposalID], iVAULT(VAULT).totalWeight(), _typeStr);
mapPID_votes[_proposalID] = 0;
mapPID_finalised[_proposalID] = true;
mapPID_finalising[_proposalID] = false;
}
//============================== BUSINESS LOGIC ================================//
function grantFunds(uint _proposalID) internal {
GrantDetails memory _grant = mapPID_grant[_proposalID];
require(_grant.amount <= iERC20(USDV).balanceOf(VAULT) / 10, "Not more than 10%");
completeProposal(_proposalID);
iVAULT(VAULT).grant(_grant.recipient, _grant.amount);
}
function moveUtils(uint _proposalID) internal {
address _proposedAddress = mapPID_address[_proposalID];
require(_proposedAddress != address(0), "No address proposed");
iVADER(VADER).changeUTILS(_proposedAddress);
completeProposal(_proposalID);
}
function moveRewardAddress(uint _proposalID) internal {
address _proposedAddress = mapPID_address[_proposalID];
require(_proposedAddress != address(0), "No address proposed");
iVADER(VADER).setRewardAddress(_proposedAddress);
completeProposal(_proposalID);
}
//============================== CONSENSUS ================================//
function countMemberVotes(uint _proposalID) internal returns (uint voteWeight){
mapPID_votes[_proposalID] -= mapPIDMember_votes[_proposalID][msg.sender];
voteWeight = iVAULT(VAULT).getMemberWeight(msg.sender);
mapPID_votes[_proposalID] += voteWeight;
mapPIDMember_votes[_proposalID][msg.sender] = voteWeight;
}
function hasMajority(uint _proposalID) public view returns(bool){
uint votes = mapPID_votes[_proposalID];
uint consensus = iVAULT(VAULT).totalWeight() / 2;
if(votes > consensus){
return true;
} else {
return false;
}
}
function hasQuorum(uint _proposalID) public view returns(bool){
uint votes = mapPID_votes[_proposalID];
uint consensus = iVAULT(VAULT).totalWeight() / 3;
if(votes > consensus){
return true;
} else {
return false;
}
}
function hasMinority(uint _proposalID) public view returns(bool){
uint votes = mapPID_votes[_proposalID];
uint consensus = iVAULT(VAULT).totalWeight() / 6;
if(votes > consensus){
return true;
} else {
return false;
}
}
function isEqual(bytes memory part1, bytes memory part2) public pure returns(bool){
if(sha256(part1) == sha256(part2)){
return true;
} else {
return false;
}
}
} | 1,813 | 200 | 2 | 1. [H-04] Proposals can be cancelled (Access control)
Anyone can cancel any proposals by calling `DAO.cancelProposal(id, id)` with `oldProposalID == newProposalID`. This always passes the minority check as the proposal was approved.
2. [H-05] Flash loans can affect governance voting in DAO.sol (Flash loans)
Function `countMemberVotes()`
3. [M-02] Undefined behavior for DAO and GRANT vote proposals in DAO.sol
Given that there are only three proposal types (GRANT, UTILS, REWARD) that are actionable, it is unclear if 'DAO' type checked in `voteProposal()` is a typographical error and should really be 'GRANT'. Otherwise, GRANT proposals will only require quorum (33%) and not majority (50%).
4. [M-13] Init function can be called by everyone (Initialization, access control) | 4 |
38_Identity.sol | // SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.7;
import "./libs/SignatureValidatorV2.sol";
contract Identity {
mapping (address => bytes32) public privileges;
// The next allowed nonce
uint public nonce = 0;
// Events
event LogPrivilegeChanged(address indexed addr, bytes32 priv);
event LogErr(address indexed to, uint value, bytes data, bytes returnData);
// only used in tryCatch
// Transaction structure
// we handle replay protection separately by requiring (address(this), chainID, nonce) as part of the sig
struct Transaction {
address to;
uint value;
bytes data;
}
constructor(address[] memory addrs) {
uint len = addrs.length;
for (uint i=0; i<len; i++) {
// @TODO should we allow setting to any arb value here?
privileges[addrs[i]] = bytes32(uint(1));
emit LogPrivilegeChanged(addrs[i], bytes32(uint(1)));
}
}
// This contract can accept ETH without calldata
receive() external payable {}
// This contract can accept ETH with calldata
// However, to support EIP 721 and EIP 1155, we need to respond to those methods with their own method signature
fallback() external payable {
bytes4 method = msg.sig;
if (
method == 0x150b7a02
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
|| method == 0xf23a6e61
// bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
|| method == 0xbc197c81
// bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
) {
// Copy back the method
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, 0x04)
return (0, 0x20)
}
}
}
function setAddrPrivilege(address addr, bytes32 priv)
external
{
require(msg.sender == address(this), 'ONLY_IDENTITY_CAN_CALL');
// Anti-bricking measure: if the privileges slot is used for special data (not 0x01),
// don't allow to set it to true
if (privileges[addr] != bytes32(0) && privileges[addr] != bytes32(uint(1)))
require(priv != bytes32(uint(1)), 'UNSETTING_SPECIAL_DATA');
privileges[addr] = priv;
emit LogPrivilegeChanged(addr, priv);
}
function tipMiner(uint amount)
external
{
require(msg.sender == address(this), 'ONLY_IDENTITY_CAN_CALL');
// See https://docs.flashbots.net/flashbots-auction/searchers/advanced/coinbase-payment/#managing-payments-to-coinbaseaddress-when-it-is-a-contract
// generally this contract is reentrancy proof cause of the nonce
executeCall(block.coinbase, amount, new bytes(0));
}
function tryCatch(address to, uint value, bytes calldata data)
external
{
require(msg.sender == address(this), 'ONLY_IDENTITY_CAN_CALL');
(bool success, bytes memory returnData) = to.call{value: value, gas: gasleft()}(data);
if (!success) emit LogErr(to, value, data, returnData);
}
// WARNING: if the signature of this is changed, we have to change IdentityFactory
function execute(Transaction[] calldata txns, bytes calldata signature)
external
{
require(txns.length > 0, 'MUST_PASS_TX');
// If we use the naive abi.encode(txn) and have a field of type `bytes`,
// there is a discrepancy between ethereumjs-abi and solidity
// @TODO check if this is resolved
uint currentNonce = nonce;
// NOTE: abi.encode is safer than abi.encodePacked in terms of collision safety
bytes32 hash = keccak256(abi.encode(address(this), block.chainid, currentNonce, txns));
// We have to increment before execution cause it protects from reentrancies
nonce = currentNonce + 1;
address signer = SignatureValidator.recoverAddrImpl(hash, signature, true);
require(privileges[signer] != bytes32(0), 'INSUFFICIENT_PRIVILEGE');
uint len = txns.length;
for (uint i=0; i<len; i++) {
Transaction memory txn = txns[i];
executeCall(txn.to, txn.value, txn.data);
}
// The actual anti-bricking mechanism - do not allow a signer to drop their own priviledges
require(privileges[signer] != bytes32(0), 'PRIVILEGE_NOT_DOWNGRADED');
}
// no need for nonce management here cause we're not dealing with sigs
function executeBySender(Transaction[] calldata txns) external {
require(txns.length > 0, 'MUST_PASS_TX');
require(privileges[msg.sender] != bytes32(0), 'INSUFFICIENT_PRIVILEGE');
uint len = txns.length;
for (uint i=0; i<len; i++) {
Transaction memory txn = txns[i];
executeCall(txn.to, txn.value, txn.data);
}
// again, anti-bricking
require(privileges[msg.sender] != bytes32(0), 'PRIVILEGE_NOT_DOWNGRADED');
}
// we shouldn't use address.call(), cause: https://github.com/ethereum/solidity/issues/2884
// copied from https://github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol
// there's also
// https://github.com/gnosis/MultiSigWallet/commit/e1b25e8632ca28e9e9e09c81bd20bf33fdb405ce
// https://github.com/austintgriffith/bouncer-proxy/blob/master/BouncerProxy/BouncerProxy.sol
// https://github.com/gnosis/safe-contracts/blob/7e2eeb3328bb2ae85c36bc11ea6afc14baeb663c/contracts/base/Executor.sol
function executeCall(address to, uint256 value, bytes memory data)
internal
{
assembly {
let result := call(gas(), to, value, add(data, 0x20), mload(data), 0, 0)
switch result case 0 {
let size := returndatasize()
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
default {}
}
// A single call consumes around 477 more gas with the pure solidity version, for whatever reason
//(bool success, bytes memory returnData) = to.call{value: value, gas: gasleft()}(data);
//if (!success) revert(string(data));
}
// EIP 1271 implementation
// see https://eips.ethereum.org/EIPS/eip-1271
function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4) {
if (privileges[SignatureValidator.recoverAddr(hash, signature)] != bytes32(0)) {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
return 0x1626ba7e;
} else {
return 0xffffffff;
}
}
// EIP 1155 implementation
// we pretty much only need to signal that we support the interface for 165, but for 1155 we also need the fallback function
function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
return
interfaceID == 0x01ffc9a7 ||
// ERC-165 support (i.e. `bytes4(keccak256('supportsInterface(bytes4)'))`).
interfaceID == 0x4e2312e0;
// ERC-1155 `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`).
}
} | 1,895 | 171 | 0 | 1. [H-01: Prevent execution with invalid signatures. (Unchecked input in `constructor`)
Suppose one of the supplied addrs[i] to the constructor of Identity.sol happens to be 0 ( by acciden).
`require (addrs[i] !=0,"Zero not allowed");`
2. [H-04] QuickAccManager Smart Contract signature verification can be exploited (Signature verification)
Several different signature modes can be used and Identity.execute forwards the signature parameter to the SignatureValidator library. The returned signer is then used for the privileges check: | 2 |
12_CompoundMultiOracle.sol | // SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.1;
import "../../utils/access/AccessControl.sol";
import "../../interfaces/vault/IOracle.sol";
import "../../constants/Constants.sol";
import "../../math/CastBytes32Bytes6.sol";
import "./CTokenInterface.sol";
contract CompoundMultiOracle is IOracle, AccessControl, Constants {
using CastBytes32Bytes6 for bytes32;
event SourceSet(bytes6 indexed baseId, bytes6 indexed kind, address indexed source);
uint public constant SCALE_FACTOR = 1;
// I think we don't need scaling for rate and chi oracles
uint8 public constant override decimals = 18;
mapping(bytes6 => mapping(bytes6 => address)) public sources;
/**
* @notice Set or reset one source
*/
function setSource(bytes6 base, bytes6 kind, address source) external auth {
_setSource(base, kind, source);
}
/**
* @notice Set or reset an oracle source
*/
function setSources(bytes6[] memory bases, bytes6[] memory kinds, address[] memory sources_) external auth {
require(bases.length == kinds.length && kinds.length == sources_.length, "Mismatched inputs");
for (uint256 i = 0; i < bases.length; i++)
_setSource(bases[i], kinds[i], sources_[i]);
}
/**
* @notice Retrieve the value of the amount at the latest oracle price.
* @return value
*/
function peek(bytes32 base, bytes32 kind, uint256 amount)
external view virtual override
returns (uint256 value, uint256 updateTime)
{
uint256 price;
(price, updateTime) = _peek(base.b6(), kind.b6());
value = price * amount / 1e18;
}
/**
* @notice Retrieve the value of the amount at the latest oracle price. Same as `peek` for this oracle.
* @return value
*/
function get(bytes32 base, bytes32 kind, uint256 amount)
external virtual override
returns (uint256 value, uint256 updateTime)
{
uint256 price;
(price, updateTime) = _peek(base.b6(), kind.b6());
value = price * amount / 1e18;
}
function _peek(bytes6 base, bytes6 kind) private view returns (uint price, uint updateTime) {
uint256 rawPrice;
address source = sources[base][kind];
require (source != address(0), "Source not found");
if (kind == RATE.b6()) rawPrice = CTokenInterface(source).borrowIndex();
else if (kind == CHI.b6()) rawPrice = CTokenInterface(source).exchangeRateStored();
else revert("Unknown oracle type");
require(rawPrice > 0, "Compound price is zero");
price = rawPrice * SCALE_FACTOR;
updateTime = block.timestamp;
}
function _setSource(bytes6 base, bytes6 kind, address source) internal {
sources[base][kind] = source;
emit SourceSet(base, kind, source);
}
} | 673 | 83 | 0 | 1. [M-04] User can redeem more tokens by artificially increasing the chi accrual. (Steal tokens)
Function `_peek()`. Line `else if (kind == "chi") rawPrice = CTokenInterface(source).exchangeRateStored();` | 1 |
45_CreditLimitByMedian.sol | //SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/ICreditLimitModel.sol";
contract CreditLimitByMedian is Ownable, ICreditLimitModel {
using Math for uint256;
bool public constant override isCreditLimitModel = true;
uint256 public override effectiveNumber;
constructor(uint256 effectiveNumber_) {
effectiveNumber = effectiveNumber_;
}
function getCreditLimit(uint256[] memory vouchs) public view override returns (uint256) {
if (vouchs.length >= effectiveNumber) {
return _findMedian(vouchs);
} else {
return 0;
}
}
function getLockedAmount(
LockedInfo[] memory array,
address account,
uint256 amount,
bool isIncrease
) public pure override returns (uint256) {
if (array.length == 0) return 0;
uint256 newLockedAmount;
if (isIncrease) {
for (uint256 i = 0; i < array.length; i++) {
uint256 remainingVouchingAmount;
if (array[i].vouchingAmount > array[i].lockedAmount) {
remainingVouchingAmount = array[i].vouchingAmount - array[i].lockedAmount;
} else {
remainingVouchingAmount = 0;
}
if (remainingVouchingAmount > array[i].availableStakingAmount) {
if (array[i].availableStakingAmount > amount) {
newLockedAmount = array[i].lockedAmount + amount;
} else {
newLockedAmount = array[i].lockedAmount + array[i].availableStakingAmount;
}
} else {
if (remainingVouchingAmount > amount) {
newLockedAmount = array[i].lockedAmount + amount;
} else {
newLockedAmount = array[i].lockedAmount + remainingVouchingAmount;
}
}
if (account == array[i].staker) {
return newLockedAmount;
}
}
} else {
for (uint256 i = 0; i < array.length; i++) {
if (array[i].lockedAmount > amount) {
newLockedAmount = array[i].lockedAmount - 1;
} else {
newLockedAmount = 0;
}
if (account == array[i].staker) {
return newLockedAmount;
}
}
}
return 0;
}
function setEffectNumber(uint256 number) external onlyOwner {
effectiveNumber = number;
}
/**
* @dev Find median from uint array
* @param array array
* @return uint256
*/
function _findMedian(uint256[] memory array) private pure returns (uint256) {
uint256[] memory arr = _sortArray(array);
if (arr.length == 0) return 0;
if (arr.length % 2 == 0) {
uint256 num1 = arr[arr.length >> 1];
uint256 num2 = arr[(arr.length >> 1) - 1];
return num1.average(num2);
} else {
return arr[arr.length >> 1];
}
}
/**
* @dev Sort uint array
* @param arr array
* @return uint256 array
*/
function _sortArray(uint256[] memory arr) private pure returns (uint256[] memory) {
uint256 length = arr.length;
for (uint256 i = 0; i < length; i++) {
for (uint256 j = i + 1; j < length; j++) {
if (arr[i] < arr[j]) {
uint256 temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
return arr;
}
} | 861 | 123 | 1 | 1. [H-02] Wrong implementation of CreditLimitByMedian.sol#getLockedAmount() makes it unable to unlock lockedAmount in CreditLimitByMedian model. (Locked amount)
Function `getLockedAmount() ` and `lockedAmount` variable
2. [M-01] Wrong implementation of CreditLimitByMedian.sol#getLockedAmount() will lock a much bigger total amount of staked tokens than expected.
Overflow
3. [M-08] MAX_TRUST_LIMIT might be too high
Both SumOfTrust.sol and CreditLimitByMedian.sol contain an expensive sort function. This is used by UserManager.sol via the functions `getLockedAmount` and `getCreditLimit`. | 3 |
100_SingleStrategyController.sol | pragma solidity =0.8.7;
import "./interfaces/IStrategy.sol";
import "./interfaces/IStrategyController.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract SingleStrategyController is
IStrategyController,
Ownable,
ReentrancyGuard
{
using SafeERC20 for IERC20;
address private _vault;
IStrategy private _strategy;
IERC20 private immutable _baseToken;
modifier onlyVault() {
require(msg.sender == _vault, "Caller is not the vault");
_;
}
constructor(IERC20 _token) {
require(address(_token) != address(0), "Zero address");
_baseToken = _token;
}
function deposit(uint256 _amount)
external
override
onlyVault
nonReentrant
{
_baseToken.safeTransferFrom(_vault, address(this), _amount);
_strategy.deposit(_baseToken.balanceOf(address(this)));
}
function withdraw(address _recipient, uint256 _amount)
external
override
onlyVault
nonReentrant
{
_strategy.withdraw(_recipient, _amount);
}
function migrate(IStrategy _newStrategy)
external
override
onlyOwner
nonReentrant
{
uint256 _oldStrategyBalance;
IStrategy _oldStrategy = _strategy;
_strategy = _newStrategy;
_baseToken.approve(address(_newStrategy), type(uint256).max);
if (address(_oldStrategy) != address(0)) {
_baseToken.approve(address(_oldStrategy), 0);
_oldStrategyBalance = _oldStrategy.totalValue();
_oldStrategy.withdraw(address(this), _oldStrategyBalance);
_newStrategy.deposit(_baseToken.balanceOf(address(this)));
}
emit StrategyMigrated(
address(_oldStrategy),
address(_newStrategy),
_oldStrategyBalance
);
}
function setVault(address _newVault) external override onlyOwner {
_vault = _newVault;
emit VaultChanged(_newVault);
}
function totalValue() external view override returns (uint256) {
return _baseToken.balanceOf(address(this)) + _strategy.totalValue();
}
function getVault() external view override returns (address) {
return _vault;
}
function getStrategy() external view override returns (IStrategy) {
return _strategy;
}
function getBaseToken() external view override returns (IERC20) {
return _baseToken;
}
} | 586 | 79 | 0 | 1. [H-01] Strategy Migration May Leave Tokens in the Old Strategy Impacting Share Calculations #L51-L72 (No checks on strategy migration Calculations)
In function `migrate()`, If a strategy does not have sufficient funds to `withdraw()` for the full amount then it is possible that tokens will be left in this yield contract during migrate()
2. [M-04] SingleStrategyController doesn't verify that new strategy uses the same base token (No checks on strategy migration Token)
When migrating from one strategy to another, the controller pulls out the funds of the old strategy and deposits them into the new one. But, it doesn't verify that both strategies use the same base token. If the new one uses a different base token, it won't "know" about the tokens it received on migration. It won't be able to deposit and transfer them. Effectively they would be lost. | 2 |
100_Collateral.sol | pragma solidity =0.8.7;
import "./interfaces/ICollateral.sol";
import "./interfaces/IStrategyController.sol";
import "./interfaces/IHook.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
contract Collateral is
ICollateral,
ERC20Upgradeable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeERC20Upgradeable for IERC20Upgradeable;
bool private _depositsAllowed;
bool private _withdrawalsAllowed;
address private _treasury;
uint256 private _mintingFee;
uint256 private _redemptionFee;
IERC20Upgradeable private _baseToken;
IStrategyController private _strategyController;
uint256 private _delayedWithdrawalExpiry;
mapping(address => WithdrawalRequest) private _accountToWithdrawalRequest;
IHook private _depositHook;
IHook private _withdrawHook;
uint256 private constant FEE_DENOMINATOR = 1000000;
uint256 private constant FEE_LIMIT = 50000;
function initialize(address _newBaseToken, address _newTreasury)
public
initializer
{
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC20_init_unchained(
string("prePO Collateral Token"),
string("preCT")
);
_baseToken = IERC20Upgradeable(_newBaseToken);
_treasury = _newTreasury;
}
function deposit(uint256 _amount)
external
override
nonReentrant
returns (uint256)
{
require(_depositsAllowed, "Deposits not allowed");
_baseToken.safeTransferFrom(msg.sender, address(this), _amount);
uint256 _amountToDeposit = _baseToken.balanceOf(address(this));
if (address(_depositHook) != address(0)) {
_depositHook.hook(msg.sender, _amount, _amountToDeposit);
}
uint256 _fee = (_amountToDeposit * _mintingFee) / FEE_DENOMINATOR + 1;
require(_amountToDeposit > _fee, "Deposit amount too small");
_baseToken.safeTransfer(_treasury, _fee);
_amountToDeposit -= _fee;
uint256 _valueBefore = _strategyController.totalValue();
_baseToken.approve(address(_strategyController), _amountToDeposit);
_strategyController.deposit(_amountToDeposit);
uint256 _valueAfter = _strategyController.totalValue();
_amountToDeposit = _valueAfter - _valueBefore;
uint256 _shares = 0;
if (totalSupply() == 0) {
_shares = _amountToDeposit;
} else {
_shares = (_amountToDeposit * totalSupply()) / (_valueBefore);
}
_mint(msg.sender, _shares);
return _shares;
}
function initiateWithdrawal(uint256 _amount) external override {
require(balanceOf(msg.sender) >= _amount, "Insufficient balance");
_accountToWithdrawalRequest[msg.sender].amount = _amount;
_accountToWithdrawalRequest[msg.sender].blockNumber = block.number;
}
function uninitiateWithdrawal() external override {
_accountToWithdrawalRequest[msg.sender].amount = 0;
_accountToWithdrawalRequest[msg.sender].blockNumber = 0;
}
function _processDelayedWithdrawal(address _account, uint256 _amount)
internal
{
require(
_accountToWithdrawalRequest[_account].amount == _amount,
"Initiated amount does not match"
);
uint256 _recordedBlock = _accountToWithdrawalRequest[_account]
.blockNumber;
require(
_recordedBlock + _delayedWithdrawalExpiry >= block.number,
"Must withdraw before expiry"
);
require(
block.number > _recordedBlock,
"Must withdraw in a later block"
);
_accountToWithdrawalRequest[_account].amount = 0;
_accountToWithdrawalRequest[_account].blockNumber = 0;
}
function withdraw(uint256 _amount)
external
override
nonReentrant
returns (uint256)
{
require(_withdrawalsAllowed, "Withdrawals not allowed");
if (_delayedWithdrawalExpiry != 0) {
_processDelayedWithdrawal(msg.sender, _amount);
}
uint256 _owed = (_strategyController.totalValue() * _amount) /
totalSupply();
_burn(msg.sender, _amount);
uint256 _balanceBefore = _baseToken.balanceOf(address(this));
_strategyController.withdraw(address(this), _owed);
uint256 _balanceAfter = _baseToken.balanceOf(address(this));
uint256 _amountWithdrawn = _balanceAfter - _balanceBefore;
if (address(_withdrawHook) != address(0)) {
_withdrawHook.hook(msg.sender, _amount, _amountWithdrawn);
}
uint256 _fee = (_amountWithdrawn * _redemptionFee) /
FEE_DENOMINATOR +
1;
require(_amountWithdrawn > _fee, "Withdrawal amount too small");
_baseToken.safeTransfer(_treasury, _fee);
_amountWithdrawn -= _fee;
_baseToken.safeTransfer(msg.sender, _amountWithdrawn);
return _amountWithdrawn;
}
function setDepositsAllowed(bool _allowed) external override onlyOwner {
_depositsAllowed = _allowed;
emit DepositsAllowedChanged(_allowed);
}
function setWithdrawalsAllowed(bool _allowed) external override onlyOwner {
_withdrawalsAllowed = _allowed;
emit WithdrawalsAllowedChanged(_allowed);
}
function setStrategyController(IStrategyController _newStrategyController)
external
override
onlyOwner
{
_strategyController = _newStrategyController;
emit StrategyControllerChanged(address(_strategyController));
}
function setDelayedWithdrawalExpiry(uint256 _newDelayedWithdrawalExpiry)
external
override
onlyOwner
{
_delayedWithdrawalExpiry = _newDelayedWithdrawalExpiry;
emit DelayedWithdrawalExpiryChanged(_delayedWithdrawalExpiry);
}
function setMintingFee(uint256 _newMintingFee)
external
override
onlyOwner
{
require(_newMintingFee <= FEE_LIMIT, "Exceeds fee limit");
_mintingFee = _newMintingFee;
emit MintingFeeChanged(_mintingFee);
}
function setRedemptionFee(uint256 _newRedemptionFee)
external
override
onlyOwner
{
require(_newRedemptionFee <= FEE_LIMIT, "Exceeds fee limit");
_redemptionFee = _newRedemptionFee;
emit RedemptionFeeChanged(_redemptionFee);
}
function setDepositHook(IHook _newDepositHook)
external
override
onlyOwner
{
_depositHook = _newDepositHook;
emit DepositHookChanged(address(_depositHook));
}
function setWithdrawHook(IHook _newWithdrawHook)
external
override
onlyOwner
{
_withdrawHook = _newWithdrawHook;
emit WithdrawHookChanged(address(_withdrawHook));
}
function getDepositsAllowed() external view override returns (bool) {
return _depositsAllowed;
}
function getWithdrawalsAllowed() external view override returns (bool) {
return _withdrawalsAllowed;
}
function getTreasury() external view override returns (address) {
return _treasury;
}
function getMintingFee() external view override returns (uint256) {
return _mintingFee;
}
function getRedemptionFee() external view override returns (uint256) {
return _redemptionFee;
}
function getBaseToken()
external
view
override
returns (IERC20Upgradeable)
{
return _baseToken;
}
function getStrategyController()
external
view
override
returns (IStrategyController)
{
return _strategyController;
}
function getDelayedWithdrawalExpiry()
external
view
override
returns (uint256)
{
return _delayedWithdrawalExpiry;
}
function getWithdrawalRequest(address _account)
external
view
override
returns (WithdrawalRequest memory)
{
return _accountToWithdrawalRequest[_account];
}
function getDepositHook() external view override returns (IHook) {
return _depositHook;
}
function getWithdrawHook() external view override returns (IHook) {
return _withdrawHook;
}
function getAmountForShares(uint256 _shares)
external
view
override
returns (uint256)
{
if (totalSupply() == 0) {
return _shares;
}
return (_shares * totalAssets()) / totalSupply();
}
function getSharesForAmount(uint256 _amount)
external
view
override
returns (uint256)
{
uint256 _totalAssets = totalAssets();
return
(_totalAssets > 0)
? ((_amount * totalSupply()) / _totalAssets)
: 0;
}
function getFeeDenominator() external pure override returns (uint256) {
return FEE_DENOMINATOR;
}
function getFeeLimit() external pure override returns (uint256) {
return FEE_LIMIT;
}
function totalAssets() public view override returns (uint256) {
return
_baseToken.balanceOf(address(this)) +
_strategyController.totalValue();
}
} | 2,219 | 276 | 0 | [H-02] First `depositor()` can break minting of shares #L82-L91 (Rounding Errors and Potential Loss of Funds)
The attack vector and impact is the same as TOB-YEARN-003, where users may not receive shares in exchange for their deposits if the total asset amount has been manipulated through a large “donation”.
[H-03] `Withdrawal` delay can be circumvented #L97
After initiating a withdrawal with `initiateWithdrawal`, it's still possible to transfer the collateral tokens. This can be used to create a second account, transfer the accounts to them and initiate withdrawals at a different time frame such that one of the accounts is always in a valid withdrawal window, no matter what time it is. If the token owner now wants to withdraw they just transfer the funds to the account that is currently in a valid withdrawal window.
[M-05] Wrong formula of `getSharesForAmount()` can potentially cause fund loss when being used to calculate the shares to be used in withdraw() (Fund loss)
In `Collateral`, the getter functions `getAmountForShares()` and `getSharesForAmount()` is using `totalAssets()` instead of `_strategyController.totalValue()`, making the results can be different than the actual shares amount needed to `withdraw()` a certain amount of _baseToken and the amount of shares expected to get by deposit() a certain amount.
| 3 |
122_Cally | pragma solidity 0.8.13;
import "solmate/utils/SafeTransferLib.sol";
import "solmate/utils/ReentrancyGuard.sol";
import "openzeppelin/access/Ownable.sol";
import "./CallyNft.sol";
contract Cally is CallyNft, ReentrancyGuard, Ownable {
using SafeTransferLib for ERC20;
using SafeTransferLib for address payable;
event NewVault(uint256 indexed vaultId, address indexed from, address indexed token);
event BoughtOption(uint256 indexed optionId, address indexed from, address indexed token);
event ExercisedOption(uint256 indexed optionId, address indexed from);
event Harvested(address indexed from, uint256 amount);
event InitiatedWithdrawal(uint256 indexed vaultId, address indexed from);
event Withdrawal(uint256 indexed vaultId, address indexed from);
enum TokenType {
ERC721,
ERC20
}
struct Vault {
uint256 tokenIdOrAmount;
address token;
uint8 premiumIndex;
uint8 durationDays;
uint8 dutchAuctionStartingStrikeIndex;
uint32 currentExpiration;
bool isExercised;
bool isWithdrawing;
TokenType tokenType;
uint256 currentStrike;
uint256 dutchAuctionReserveStrike;
}
uint32 public constant AUCTION_DURATION = 24 hours;
uint256[] public premiumOptions = [0.01 ether, 0.025 ether, 0.05 ether, 0.075 ether, 0.1 ether, 0.25 ether, 0.5 ether, 0.75 ether, 1.0 ether, 2.5 ether, 5.0 ether, 7.5 ether, 10 ether, 25 ether, 50 ether, 75 ether, 100 ether];
uint256[] public strikeOptions = [1 ether, 2 ether, 3 ether, 5 ether, 8 ether, 13 ether, 21 ether, 34 ether, 55 ether, 89 ether, 144 ether, 233 ether, 377 ether, 610 ether, 987 ether, 1597 ether, 2584 ether, 4181 ether, 6765 ether];
uint256 public feeRate = 0;
uint256 public protocolUnclaimedFees = 0;
uint256 public vaultIndex = 1;
mapping(uint256 => Vault) private _vaults;
mapping(uint256 => address) private _vaultBeneficiaries;
mapping(address => uint256) public ethBalance;
function setFee(uint256 feeRate_) external onlyOwner {
feeRate = feeRate_;
}
function withdrawProtocolFees() external onlyOwner returns (uint256 amount) {
amount = protocolUnclaimedFees;
protocolUnclaimedFees = 0;
payable(msg.sender).safeTransferETH(amount);
}
function createVault(
uint256 tokenIdOrAmount,
address token,
uint8 premiumIndex,
uint8 durationDays,
uint8 dutchAuctionStartingStrikeIndex,
uint256 dutchAuctionReserveStrike,
TokenType tokenType
) external returns (uint256 vaultId) {
require(premiumIndex < premiumOptions.length, "Invalid premium index");
require(dutchAuctionStartingStrikeIndex < strikeOptions.length, "Invalid strike index");
require(dutchAuctionReserveStrike < strikeOptions[dutchAuctionStartingStrikeIndex], "Reserve strike too small");
require(durationDays > 0, "durationDays too small");
require(tokenType == TokenType.ERC721 || tokenType == TokenType.ERC20, "Invalid token type");
Vault memory vault = Vault({
tokenIdOrAmount: tokenIdOrAmount,
token: token,
premiumIndex: premiumIndex,
durationDays: durationDays,
dutchAuctionStartingStrikeIndex: dutchAuctionStartingStrikeIndex,
currentExpiration: uint32(block.timestamp),
isExercised: false,
isWithdrawing: false,
tokenType: tokenType,
currentStrike: 0,
dutchAuctionReserveStrike: dutchAuctionReserveStrike
});
vaultIndex += 2;
vaultId = vaultIndex;
_vaults[vaultId] = vault;
_mint(msg.sender, vaultId);
emit NewVault(vaultId, msg.sender, token);
vault.tokenType == TokenType.ERC721
? ERC721(vault.token).transferFrom(msg.sender, address(this), vault.tokenIdOrAmount)
: ERC20(vault.token).safeTransferFrom(msg.sender, address(this), vault.tokenIdOrAmount);
}
function buyOption(uint256 vaultId) external payable returns (uint256 optionId) {
Vault memory vault = _vaults[vaultId];
require(vaultId % 2 != 0, "Not vault type");
require(ownerOf(vaultId) != address(0), "Vault does not exist");
require(vault.isExercised == false, "Vault already exercised");
require(vault.isWithdrawing == false, "Vault is being withdrawn");
uint256 premium = getPremium(vaultId);
require(msg.value >= premium, "Incorrect ETH amount sent");
uint32 auctionStartTimestamp = vault.currentExpiration;
require(block.timestamp >= auctionStartTimestamp, "Auction not started");
vault.currentStrike = getDutchAuctionStrike(
strikeOptions[vault.dutchAuctionStartingStrikeIndex],
vault.currentExpiration + AUCTION_DURATION,
vault.dutchAuctionReserveStrike
);
vault.currentExpiration = uint32(block.timestamp) + (vault.durationDays * 1 days);
_vaults[vaultId] = vault;
optionId = vaultId + 1;
_forceTransfer(msg.sender, optionId);
address beneficiary = getVaultBeneficiary(vaultId);
ethBalance[beneficiary] += msg.value;
emit BoughtOption(optionId, msg.sender, vault.token);
}
function exercise(uint256 optionId) external payable {
require(optionId % 2 == 0, "Not option type");
require(msg.sender == ownerOf(optionId), "You are not the owner");
uint256 vaultId = optionId - 1;
Vault memory vault = _vaults[vaultId];
require(block.timestamp < vault.currentExpiration, "Option has expired");
require(msg.value == vault.currentStrike, "Incorrect ETH sent for strike");
_burn(optionId);
vault.isExercised = true;
_vaults[vaultId] = vault;
uint256 fee = 0;
if (feeRate > 0) {
fee = (msg.value * feeRate) / 1e18;
protocolUnclaimedFees += fee;
}
ethBalance[getVaultBeneficiary(vaultId)] += msg.value - fee;
emit ExercisedOption(optionId, msg.sender);
vault.tokenType == TokenType.ERC721
? ERC721(vault.token).transferFrom(address(this), msg.sender, vault.tokenIdOrAmount)
: ERC20(vault.token).safeTransfer(msg.sender, vault.tokenIdOrAmount);
}
function initiateWithdraw(uint256 vaultId) external {
require(vaultId % 2 != 0, "Not vault type");
require(msg.sender == ownerOf(vaultId), "You are not the owner");
_vaults[vaultId].isWithdrawing = true;
emit InitiatedWithdrawal(vaultId, msg.sender);
}
function withdraw(uint256 vaultId) external nonReentrant {
require(vaultId % 2 != 0, "Not vault type");
require(msg.sender == ownerOf(vaultId), "You are not the owner");
Vault memory vault = _vaults[vaultId];
require(vault.isExercised == false, "Vault already exercised");
require(vault.isWithdrawing, "Vault not in withdrawable state");
require(block.timestamp > vault.currentExpiration, "Option still active");
uint256 optionId = vaultId + 1;
_burn(optionId);
_burn(vaultId);
emit Withdrawal(vaultId, msg.sender);
harvest();
vault.tokenType == TokenType.ERC721
? ERC721(vault.token).transferFrom(address(this), msg.sender, vault.tokenIdOrAmount)
: ERC20(vault.token).safeTransfer(msg.sender, vault.tokenIdOrAmount);
}
function setVaultBeneficiary(uint256 vaultId, address beneficiary) external {
require(vaultId % 2 != 0, "Not vault type");
require(msg.sender == ownerOf(vaultId), "Not owner");
_vaultBeneficiaries[vaultId] = beneficiary;
}
function harvest() public returns (uint256 amount) {
amount = ethBalance[msg.sender];
ethBalance[msg.sender] = 0;
emit Harvested(msg.sender, amount);
payable(msg.sender).safeTransferETH(amount);
}
function getVaultBeneficiary(uint256 vaultId) public view returns (address beneficiary) {
address currentBeneficiary = _vaultBeneficiaries[vaultId];
return currentBeneficiary == address(0) ? ownerOf(vaultId) : currentBeneficiary;
}
function vaults(uint256 vaultId) external view returns (Vault memory) {
return _vaults[vaultId];
}
function getPremium(uint256 vaultId) public view returns (uint256 premium) {
Vault memory vault = _vaults[vaultId];
return premiumOptions[vault.premiumIndex];
}
function getDutchAuctionStrike(
uint256 startingStrike,
uint32 auctionEndTimestamp,
uint256 reserveStrike
) public view returns (uint256 strike) {
uint256 delta = auctionEndTimestamp > block.timestamp ? auctionEndTimestamp - block.timestamp : 0;
uint256 progress = (1e18 * delta) / AUCTION_DURATION;
uint256 auctionStrike = (progress * progress * startingStrike) / (1e18 * 1e18);
strike = auctionStrike > reserveStrike ? auctionStrike : reserveStrike;
}
function transferFrom(
address from,
address to,
uint256 id
) public override {
require(from == _ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(
msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
"NOT_AUTHORIZED"
);
bool isVaultToken = id % 2 != 0;
if (isVaultToken) {
_vaultBeneficiaries[id] = address(0);
}
_ownerOf[id] = to;
delete getApproved[id];
emit Transfer(from, to, id);
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_ownerOf[tokenId] != address(0), "URI query for NOT_MINTED token");
bool isVaultToken = tokenId % 2 != 0;
Vault memory vault = _vaults[isVaultToken ? tokenId : tokenId - 1];
string memory jsonStr = renderJson(
vault.token,
vault.tokenIdOrAmount,
getPremium(vault.premiumIndex),
vault.durationDays,
strikeOptions[vault.dutchAuctionStartingStrikeIndex],
vault.currentExpiration,
vault.currentStrike,
vault.isExercised,
isVaultToken
);
return string(abi.encodePacked("data:application/json;base64,", Base64.encode(bytes(jsonStr))));
}
} | 2,481 | 219 | 2 | 1. [H-01] no-revert-on-transfer ERC20 tokens can be drained #L198-L200 (Unchecked Return Values, ERC20/ERC721 token handling)
Some ERC20 tokens don't throw but just return false when a transfer fails. This can be abused to trick the `createVault()` function to initialize the vault without providing any tokens.
2. [H-03] [WP-H0] Fake balances can be created for not-yet-existing ERC20 tokens, which allows attackers to set traps to steal funds from future users L158-L201
When creating a new vault, solmate's SafeTransferLib is used for pulling `vault.token` from the caller's account, this issue won't exist if OpenZeppelin's SafeERC20 is used instead.
3. [M-02] It shouldn’t be possible to create a vault with Cally’ own token #L193 L199
Currently it’s possible to create an ERC-721 vault using Cally’ own address as token, and using the freshly minted vault id as tokenIdOrAmount. This results in a new vault whose ownership is passed to Cally contract immediately upon creation.
4. [M-04] Vaults steal rebasing tokens' rewards. # L172-L200
Rebasing tokens are tokens that have each holder's `balanceof()` increase over time. Aave aTokens are an example of such tokens.
If rebasing tokens are used as the vault token, rewards accrue to the vault and cannot be withdrawn by either the option seller or the owner, and remain locked forever.
5. [M-06] Owner can set the feeRate to be greater than 100% and cause all future calls to exercise to revert (Centralization Risks)
The owner can force options to be non-exercisable, collecting premium without risking the loss of their NFT/tokens
6. [M-08] Vault is Not Compatible with Fee Tokens and Vaults with Such Tokens Could Be Exploited (Missing Input Validation, Token Loss/Asset)
Some ERC20 tokens charge a transaction fee for every transfer (used to encourage staking, add to liquidity pool, pay a fee to contract owner, etc.). If any such token is used in the `createVault()` function, either the token cannot be withdrawn from the contract (due to insufficient token balance), or it could be exploited by other such token holders and the `Cally` contract would lose economic value and some users would be unable to withdraw the underlying asset.
7. [M-09] Use safeTransferFrom instead of transferFrom for ERC721 transfers (Unchecked external values, Unsafe safeTransferFrom)
8. [M-10] `createVault()` does not confirm whether tokenType and token’s type are the same (Token type swap)
If token is an ERC20 token and the user uses TokenType.ERC721 as tokenType. It is less harmful, since ERC721(vault.token).transferFrom(msg.sender, address(this), vault.tokenIdOrAmount) still works when vault.token is actually ERC20 token. | 8 |
109_AxelarGateway.sol | pragma solidity 0.8.9;
import { IAxelarGateway } from './interfaces/IAxelarGateway.sol';
import { IERC20 } from './interfaces/IERC20.sol';
import { IERC20BurnFrom } from './interfaces/IERC20BurnFrom.sol';
import { BurnableMintableCappedERC20 } from './BurnableMintableCappedERC20.sol';
import { DepositHandler } from './DepositHandler.sol';
import { AdminMultisigBase } from './AdminMultisigBase.sol';
import { TokenDeployer } from './TokenDeployer.sol';
abstract contract AxelarGateway is IAxelarGateway, AdminMultisigBase {
error NotSelf();
error InvalidCodeHash();
error SetupFailed();
error InvalidAmount();
error TokenDoesNotExist(string symbol);
error TokenAlreadyExists(string symbol);
error TokenDeployFailed(string symbol);
error TokenContractDoesNotExist(address token);
error BurnFailed(string symbol);
error MintFailed(string symbol);
error TokenIsFrozen(string symbol);
enum Role {
Admin,
Owner,
Operator
}
enum TokenType {
InternalBurnable,
InternalBurnableFrom,
External
}
bytes32 internal constant KEY_IMPLEMENTATION =
bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc);
bytes32 internal constant KEY_ALL_TOKENS_FROZEN = keccak256('all-tokens-frozen');
bytes32 internal constant PREFIX_COMMAND_EXECUTED = keccak256('command-executed');
bytes32 internal constant PREFIX_TOKEN_ADDRESS = keccak256('token-address');
bytes32 internal constant PREFIX_TOKEN_TYPE = keccak256('token-type');
bytes32 internal constant PREFIX_TOKEN_FROZEN = keccak256('token-frozen');
bytes32 internal constant PREFIX_CONTRACT_CALL_APPROVED = keccak256('contract-call-approved');
bytes32 internal constant PREFIX_CONTRACT_CALL_APPROVED_WITH_MINT = keccak256('contract-call-approved-with-mint');
bytes32 internal constant SELECTOR_BURN_TOKEN = keccak256('burnToken');
bytes32 internal constant SELECTOR_DEPLOY_TOKEN = keccak256('deployToken');
bytes32 internal constant SELECTOR_MINT_TOKEN = keccak256('mintToken');
bytes32 internal constant SELECTOR_APPROVE_CONTRACT_CALL = keccak256('approveContractCall');
bytes32 internal constant SELECTOR_APPROVE_CONTRACT_CALL_WITH_MINT = keccak256('approveContractCallWithMint');
bytes32 internal constant SELECTOR_TRANSFER_OPERATORSHIP = keccak256('transferOperatorship');
bytes32 internal constant SELECTOR_TRANSFER_OWNERSHIP = keccak256('transferOwnership');
uint8 internal constant OLD_KEY_RETENTION = 16;
address internal immutable TOKEN_DEPLOYER_IMPLEMENTATION;
constructor(address tokenDeployerImplementation) {
TOKEN_DEPLOYER_IMPLEMENTATION = tokenDeployerImplementation;
}
modifier onlySelf() {
if (msg.sender != address(this)) revert NotSelf();
_;
}
function sendToken(
string memory destinationChain,
string memory destinationAddress,
string memory symbol,
uint256 amount
) external {
_burnTokenFrom(msg.sender, symbol, amount);
emit TokenSent(msg.sender, destinationChain, destinationAddress, symbol, amount);
}
function callContract(
string memory destinationChain,
string memory destinationContractAddress,
bytes memory payload
) external {
emit ContractCall(msg.sender, destinationChain, destinationContractAddress, keccak256(payload), payload);
}
function callContractWithToken(
string memory destinationChain,
string memory destinationContractAddress,
bytes memory payload,
string memory symbol,
uint256 amount
) external {
_burnTokenFrom(msg.sender, symbol, amount);
emit ContractCallWithToken(
msg.sender,
destinationChain,
destinationContractAddress,
keccak256(payload),
payload,
symbol,
amount
);
}
function isContractCallApproved(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash
) external view override returns (bool) {
return
getBool(_getIsContractCallApprovedKey(commandId, sourceChain, sourceAddress, contractAddress, payloadHash));
}
function isContractCallAndMintApproved(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash,
string memory symbol,
uint256 amount
) external view override returns (bool) {
return
getBool(
_getIsContractCallApprovedWithMintKey(
commandId,
sourceChain,
sourceAddress,
contractAddress,
payloadHash,
symbol,
amount
)
);
}
function validateContractCall(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
bytes32 payloadHash
) external override returns (bool valid) {
bytes32 key = _getIsContractCallApprovedKey(commandId, sourceChain, sourceAddress, msg.sender, payloadHash);
valid = getBool(key);
if (valid) _setBool(key, false);
}
function validateContractCallAndMint(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
bytes32 payloadHash,
string memory symbol,
uint256 amount
) external override returns (bool valid) {
bytes32 key = _getIsContractCallApprovedWithMintKey(
commandId,
sourceChain,
sourceAddress,
msg.sender,
payloadHash,
symbol,
amount
);
valid = getBool(key);
if (valid) {
_setBool(key, false);
_mintToken(symbol, msg.sender, amount);
}
}
function allTokensFrozen() public view override returns (bool) {
return getBool(KEY_ALL_TOKENS_FROZEN);
}
function implementation() public view override returns (address) {
return getAddress(KEY_IMPLEMENTATION);
}
function tokenAddresses(string memory symbol) public view override returns (address) {
return getAddress(_getTokenAddressKey(symbol));
}
function tokenFrozen(string memory symbol) public view override returns (bool) {
return getBool(_getFreezeTokenKey(symbol));
}
function isCommandExecuted(bytes32 commandId) public view override returns (bool) {
return getBool(_getIsCommandExecutedKey(commandId));
}
function adminEpoch() external view override returns (uint256) {
return _adminEpoch();
}
function adminThreshold(uint256 epoch) external view override returns (uint256) {
return _getAdminThreshold(epoch);
}
function admins(uint256 epoch) external view override returns (address[] memory results) {
uint256 adminCount = _getAdminCount(epoch);
results = new address[](adminCount);
for (uint256 i; i < adminCount; i++) {
results[i] = _getAdmin(epoch, i);
}
}
function freezeToken(string memory symbol) external override onlyAdmin {
_setBool(_getFreezeTokenKey(symbol), true);
emit TokenFrozen(symbol);
}
function unfreezeToken(string memory symbol) external override onlyAdmin {
_setBool(_getFreezeTokenKey(symbol), false);
emit TokenUnfrozen(symbol);
}
function freezeAllTokens() external override onlyAdmin {
_setBool(KEY_ALL_TOKENS_FROZEN, true);
emit AllTokensFrozen();
}
function unfreezeAllTokens() external override onlyAdmin {
_setBool(KEY_ALL_TOKENS_FROZEN, false);
emit AllTokensUnfrozen();
}
function upgrade(
address newImplementation,
bytes32 newImplementationCodeHash,
bytes calldata setupParams
) external override onlyAdmin {
if (newImplementationCodeHash != newImplementation.codehash) revert InvalidCodeHash();
emit Upgraded(newImplementation);
if (setupParams.length > 0) {
(bool success, ) = newImplementation.delegatecall(
abi.encodeWithSelector(IAxelarGateway.setup.selector, setupParams)
);
if (!success) revert SetupFailed();
}
_setImplementation(newImplementation);
}
function _burnTokenFrom(
address sender,
string memory symbol,
uint256 amount
) internal {
address tokenAddress = tokenAddresses(symbol);
if (tokenAddress == address(0)) revert TokenDoesNotExist(symbol);
if (amount == 0) revert InvalidAmount();
TokenType tokenType = _getTokenType(symbol);
bool burnSuccess;
if (tokenType == TokenType.External) {
_checkTokenStatus(symbol);
burnSuccess = _callERC20Token(
tokenAddress,
abi.encodeWithSelector(IERC20.transferFrom.selector, sender, address(this), amount)
);
if (!burnSuccess) revert BurnFailed(symbol);
return;
}
if (tokenType == TokenType.InternalBurnableFrom) {
burnSuccess = _callERC20Token(
tokenAddress,
abi.encodeWithSelector(IERC20BurnFrom.burnFrom.selector, sender, amount)
);
if (!burnSuccess) revert BurnFailed(symbol);
return;
}
burnSuccess = _callERC20Token(
tokenAddress,
abi.encodeWithSelector(
IERC20.transferFrom.selector,
sender,
BurnableMintableCappedERC20(tokenAddress).depositAddress(bytes32(0)),
amount
)
);
if (!burnSuccess) revert BurnFailed(symbol);
BurnableMintableCappedERC20(tokenAddress).burn(bytes32(0));
}
function _deployToken(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap,
address tokenAddress
) internal {
if (tokenAddresses(symbol) != address(0)) revert TokenAlreadyExists(symbol);
if (tokenAddress == address(0)) {
bytes32 salt = keccak256(abi.encodePacked(symbol));
(bool success, bytes memory data) = TOKEN_DEPLOYER_IMPLEMENTATION.delegatecall(
abi.encodeWithSelector(TokenDeployer.deployToken.selector, name, symbol, decimals, cap, salt)
);
if (!success) revert TokenDeployFailed(symbol);
tokenAddress = abi.decode(data, (address));
_setTokenType(symbol, TokenType.InternalBurnableFrom);
} else {
if (tokenAddress.code.length == uint256(0)) revert TokenContractDoesNotExist(tokenAddress);
_setTokenType(symbol, TokenType.External);
}
_setTokenAddress(symbol, tokenAddress);
emit TokenDeployed(symbol, tokenAddress);
}
function _mintToken(
string memory symbol,
address account,
uint256 amount
) internal {
address tokenAddress = tokenAddresses(symbol);
if (tokenAddress == address(0)) revert TokenDoesNotExist(symbol);
if (_getTokenType(symbol) == TokenType.External) {
_checkTokenStatus(symbol);
bool success = _callERC20Token(
tokenAddress,
abi.encodeWithSelector(IERC20.transfer.selector, account, amount)
);
if (!success) revert MintFailed(symbol);
} else {
BurnableMintableCappedERC20(tokenAddress).mint(account, amount);
}
}
function _burnToken(string memory symbol, bytes32 salt) internal {
address tokenAddress = tokenAddresses(symbol);
if (tokenAddress == address(0)) revert TokenDoesNotExist(symbol);
if (_getTokenType(symbol) == TokenType.External) {
_checkTokenStatus(symbol);
DepositHandler depositHandler = new DepositHandler{ salt: salt }();
(bool success, bytes memory returnData) = depositHandler.execute(
tokenAddress,
abi.encodeWithSelector(
IERC20.transfer.selector,
address(this),
IERC20(tokenAddress).balanceOf(address(depositHandler))
)
);
if (!success || (returnData.length != uint256(0) && !abi.decode(returnData, (bool))))
revert BurnFailed(symbol);
depositHandler.destroy(address(this));
} else {
BurnableMintableCappedERC20(tokenAddress).burn(salt);
}
}
function _approveContractCall(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash,
bytes32 sourceTxHash,
uint256 sourceEventIndex
) internal {
_setContractCallApproved(commandId, sourceChain, sourceAddress, contractAddress, payloadHash);
emit ContractCallApproved(
commandId,
sourceChain,
sourceAddress,
contractAddress,
payloadHash,
sourceTxHash,
sourceEventIndex
);
}
function _approveContractCallWithMint(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash,
string memory symbol,
uint256 amount,
bytes32 sourceTxHash,
uint256 sourceEventIndex
) internal {
_setContractCallApprovedWithMint(
commandId,
sourceChain,
sourceAddress,
contractAddress,
payloadHash,
symbol,
amount
);
emit ContractCallApprovedWithMint(
commandId,
sourceChain,
sourceAddress,
contractAddress,
payloadHash,
symbol,
amount,
sourceTxHash,
sourceEventIndex
);
}
function _getTokenTypeKey(string memory symbol) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PREFIX_TOKEN_TYPE, symbol));
}
function _getFreezeTokenKey(string memory symbol) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PREFIX_TOKEN_FROZEN, symbol));
}
function _getTokenAddressKey(string memory symbol) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PREFIX_TOKEN_ADDRESS, symbol));
}
function _getIsCommandExecutedKey(bytes32 commandId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PREFIX_COMMAND_EXECUTED, commandId));
}
function _getIsContractCallApprovedKey(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
PREFIX_CONTRACT_CALL_APPROVED,
commandId,
sourceChain,
sourceAddress,
contractAddress,
payloadHash
)
);
}
function _getIsContractCallApprovedWithMintKey(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash,
string memory symbol,
uint256 amount
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
PREFIX_CONTRACT_CALL_APPROVED_WITH_MINT,
commandId,
sourceChain,
sourceAddress,
contractAddress,
payloadHash,
symbol,
amount
)
);
}
function _callERC20Token(address tokenAddress, bytes memory callData) internal returns (bool) {
(bool success, bytes memory returnData) = tokenAddress.call(callData);
return success && (returnData.length == uint256(0) || abi.decode(returnData, (bool)));
}
function _getTokenType(string memory symbol) internal view returns (TokenType) {
return TokenType(getUint(_getTokenTypeKey(symbol)));
}
function _checkTokenStatus(string memory symbol) internal view {
if (getBool(_getFreezeTokenKey(symbol)) || getBool(KEY_ALL_TOKENS_FROZEN)) revert TokenIsFrozen(symbol);
}
function _setTokenType(string memory symbol, TokenType tokenType) internal {
_setUint(_getTokenTypeKey(symbol), uint256(tokenType));
}
function _setTokenAddress(string memory symbol, address tokenAddress) internal {
_setAddress(_getTokenAddressKey(symbol), tokenAddress);
}
function _setCommandExecuted(bytes32 commandId, bool executed) internal {
_setBool(_getIsCommandExecutedKey(commandId), executed);
}
function _setContractCallApproved(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash
) internal {
_setBool(
_getIsContractCallApprovedKey(commandId, sourceChain, sourceAddress, contractAddress, payloadHash),
true
);
}
function _setContractCallApprovedWithMint(
bytes32 commandId,
string memory sourceChain,
string memory sourceAddress,
address contractAddress,
bytes32 payloadHash,
string memory symbol,
uint256 amount
) internal {
_setBool(
_getIsContractCallApprovedWithMintKey(
commandId,
sourceChain,
sourceAddress,
contractAddress,
payloadHash,
symbol,
amount
),
true
);
}
function _setImplementation(address newImplementation) internal {
_setAddress(KEY_IMPLEMENTATION, newImplementation);
}
} | 3,720 | 477 | 1 | 1. [M-01] Low level call returns true if the address doesn't exist (Unchecked Return Values)
#L545-L548
The low-level functions `call` and `delegatecall` are used in some places in the code and it can be problematic. For example, in the `_callERC20Token` of the AxelarGateway contract there is a low level call in order to call the ERC20 functions, but if the given tokenAddress doesn't exist success will be equal to true and the function will return true and the code execution will be continued like the call was successful.
2. [M-02] User's funds can get lost when transferring to other chain (Insufficient Validation in _callERC20Token )
#L384-L389
if the AxelarGateway doesn't have the needed amount of token for some reason, the `_callERC20Token` with the `transfer` function selector will fail and return false, which will make the `_mintToken` function revert. Because it reverted, the user won't get his funds on the destination chain, although he payed the needed amount in the source chain.
3. [M-04] Unsupported fee-on-transfer tokens
When tokenAddress is fee-on-transfer tokens, in the `_burnTokenFrom` function, the actual amount of tokens received by the contract will be less than the amount. | 3 |
114_AaveV3YieldSource.sol | pragma solidity 0.8.10;
import { IAToken } from "@aave/core-v3/contracts/interfaces/IAToken.sol";
import { IPool } from "@aave/core-v3/contracts/interfaces/IPool.sol";
import { IPoolAddressesProvider } from "@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol";
import { IPoolAddressesProviderRegistry } from "@aave/core-v3/contracts/interfaces/IPoolAddressesProviderRegistry.sol";
import { IRewardsController } from "@aave/periphery-v3/contracts/rewards/interfaces/IRewardsController.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Manageable, Ownable } from "@pooltogether/owner-manager-contracts/contracts/Manageable.sol";
import { IYieldSource } from "@pooltogether/yield-source-interface/contracts/IYieldSource.sol";
contract AaveV3YieldSource is ERC20, IYieldSource, Manageable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event AaveV3YieldSourceInitialized(
IAToken indexed aToken,
IRewardsController rewardsController,
IPoolAddressesProviderRegistry poolAddressesProviderRegistry,
string name,
string symbol,
uint8 decimals,
address owner
);
event SuppliedTokenTo(address indexed from, uint256 shares, uint256 amount, address indexed to);
event RedeemedToken(address indexed from, uint256 shares, uint256 amount);
event Claimed(
address indexed from,
address indexed to,
address[] rewardsList,
uint256[] claimedAmounts
);
event DecreasedERC20Allowance(
address indexed from,
address indexed spender,
uint256 amount,
IERC20 indexed token
);
event IncreasedERC20Allowance(
address indexed from,
address indexed spender,
uint256 amount,
IERC20 indexed token
);
event TransferredERC20(
address indexed from,
address indexed to,
uint256 amount,
IERC20 indexed token
);
IAToken public aToken;
IRewardsController public rewardsController;
IPoolAddressesProviderRegistry public poolAddressesProviderRegistry;
uint8 private immutable _decimals;
uint256 private constant ADDRESSES_PROVIDER_ID = uint256(0);
uint16 private constant REFERRAL_CODE = uint16(188);
constructor(
IAToken _aToken,
IRewardsController _rewardsController,
IPoolAddressesProviderRegistry _poolAddressesProviderRegistry,
string memory _name,
string memory _symbol,
uint8 decimals_,
address _owner
) Ownable(_owner) ERC20(_name, _symbol) ReentrancyGuard() {
require(address(_aToken) != address(0), "AaveV3YS/aToken-not-zero-address");
aToken = _aToken;
require(address(_rewardsController) != address(0), "AaveV3YS/RC-not-zero-address");
rewardsController = _rewardsController;
require(address(_poolAddressesProviderRegistry) != address(0), "AaveV3YS/PR-not-zero-address");
poolAddressesProviderRegistry = _poolAddressesProviderRegistry;
require(_owner != address(0), "AaveV3YS/owner-not-zero-address");
require(decimals_ > 0, "AaveV3YS/decimals-gt-zero");
_decimals = decimals_;
IERC20(_tokenAddress()).safeApprove(address(_pool()), type(uint256).max);
emit AaveV3YieldSourceInitialized(
_aToken,
_rewardsController,
_poolAddressesProviderRegistry,
_name,
_symbol,
decimals_,
_owner
);
}
function balanceOfToken(address _user) external override returns (uint256) {
return _sharesToToken(balanceOf(_user));
}
function depositToken() public view override returns (address) {
return _tokenAddress();
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
function supplyTokenTo(uint256 _depositAmount, address _to) external override nonReentrant {
uint256 _shares = _tokenToShares(_depositAmount);
require(_shares > 0, "AaveV3YS/shares-gt-zero");
address _underlyingAssetAddress = _tokenAddress();
IERC20(_underlyingAssetAddress).safeTransferFrom(msg.sender, address(this), _depositAmount);
_pool().supply(_underlyingAssetAddress, _depositAmount, address(this), REFERRAL_CODE);
_mint(_to, _shares);
emit SuppliedTokenTo(msg.sender, _shares, _depositAmount, _to);
}
function redeemToken(uint256 _redeemAmount) external override nonReentrant returns (uint256) {
address _underlyingAssetAddress = _tokenAddress();
IERC20 _assetToken = IERC20(_underlyingAssetAddress);
uint256 _shares = _tokenToShares(_redeemAmount);
_burn(msg.sender, _shares);
uint256 _beforeBalance = _assetToken.balanceOf(address(this));
_pool().withdraw(_underlyingAssetAddress, _redeemAmount, address(this));
uint256 _afterBalance = _assetToken.balanceOf(address(this));
uint256 _balanceDiff = _afterBalance.sub(_beforeBalance);
_assetToken.safeTransfer(msg.sender, _balanceDiff);
emit RedeemedToken(msg.sender, _shares, _redeemAmount);
return _balanceDiff;
}
function claimRewards(address _to) external onlyManagerOrOwner returns (bool) {
require(_to != address(0), "AaveV3YS/payee-not-zero-address");
address[] memory _assets = new address[](1);
_assets[0] = address(aToken);
(address[] memory _rewardsList, uint256[] memory _claimedAmounts) = rewardsController
.claimAllRewards(_assets, _to);
emit Claimed(msg.sender, _to, _rewardsList, _claimedAmounts);
return true;
}
function decreaseERC20Allowance(
IERC20 _token,
address _spender,
uint256 _amount
) external onlyManagerOrOwner {
_requireNotAToken(address(_token));
_token.safeDecreaseAllowance(_spender, _amount);
emit DecreasedERC20Allowance(msg.sender, _spender, _amount, _token);
}
function increaseERC20Allowance(
IERC20 _token,
address _spender,
uint256 _amount
) external onlyManagerOrOwner {
_requireNotAToken(address(_token));
_token.safeIncreaseAllowance(_spender, _amount);
emit IncreasedERC20Allowance(msg.sender, _spender, _amount, _token);
}
function transferERC20(
IERC20 _token,
address _to,
uint256 _amount
) external onlyManagerOrOwner {
require(address(_token) != address(aToken), "AaveV3YS/forbid-aToken-transfer");
_token.safeTransfer(_to, _amount);
emit TransferredERC20(msg.sender, _to, _amount, _token);
}
function _requireNotAToken(address _token) internal view {
require(_token != address(aToken), "AaveV3YS/forbid-aToken-allowance");
}
function _tokenToShares(uint256 _tokens) internal view returns (uint256) {
uint256 _supply = totalSupply();
return _supply == 0 ? _tokens : _tokens.mul(_supply).div(aToken.balanceOf(address(this)));
}
function _sharesToToken(uint256 _shares) internal view returns (uint256) {
uint256 _supply = totalSupply();
return _supply == 0 ? _shares : _shares.mul(aToken.balanceOf(address(this))).div(_supply);
}
function _tokenAddress() internal view returns (address) {
return aToken.UNDERLYING_ASSET_ADDRESS();
}
function _poolProvider() internal view returns (IPoolAddressesProvider) {
return
IPoolAddressesProvider(
poolAddressesProviderRegistry.getAddressesProvidersList()[ADDRESSES_PROVIDER_ID]
);
}
function _pool() internal view returns (IPool) {
return IPool(_poolProvider().getPool());
}
} | 1,926 | 177 | 2 | 1. [H-01] A malicious early user/attacker can manipulate the vault's `pricePerShare` to take an unfair share of future users' deposits (Lack of access control, Price manipulation)
#L352-L374
A malicious early user can `supplyTokenTo()` with 1 wei of `_underlyingAssetAddress` token as the first depositor of the AaveV3YieldSource.sol, and get 1 wei of shares token.
Then the attacker can send `10000e18 - 1` of `aToken` and inflate the price per share from `1.0000` to an extreme value of 1.0000e22 ( from (1 + 10000e18 - 1) / 1) .
As a result, the future user who deposits 19999e18 will only receive 1 wei (from 19999e18 * 1 / 10000e18) of shares token.
They will immediately lose 9999e18 or half of their deposits if they `redeemToken()` right after the `supplyTokenTo()`.
2. [M-01] User fund loss in `supplyTokenTo()` because of rounding (Rounding Errors and Potential Loss of Funds)
#L231-L242, #L357-L362
When user use `supplyTokenTo()` to deposit his tokens and get share in FeildSource because of rounding in division user gets lower amount of share. for example if token's _decimal was 1 and totalSupply() was 1000 and aToken.balanceOf(FieldSource.address) was 2100 (becasue of profits in Aave Pool balance is higher than supply), then if user deposit 4 token to the contract with supplyTokenTo(), contract is going to mint only 1 share for that user and if user calls YeildToken.balanceOf(user) the return value is going to be 2 and user already lost half of his deposit.
3. [M-02] `_depositAmount` requires to be updated to contract balance increase (Unchecked transfer, Unchecked Token Transfers)
#L231-L242
Every time `transferFrom` or `transfer` function in ERC20 standard is called there is a possibility that underlying smart contract did not transfer the exact amount entered.
4. [M-03] Owner or Managers can rug Aave rewards (Centralization risks)
#L275-L282
A malicious owner or manager can steal all Aave rewards that are meant for PoolTogether users.
5. [M-04] RewardsController Emission Manager Can Authorize Users to Claim on Behalf of the AaveV3YieldSource Contract and Siphon Yield (Authorize)
#L275-L286
The AaveV3YieldSource contract allows the manager or owner of the contract to claim rewards from Aave's rewards controller. However, there is an external dependency on this periphery Aave contract such that the emission manager of the `RewardsController` contract may allows other users to be authorized claimers.
6. [M-05] Yield source does not correctly calculate share conversions (Incorrect share conversions )
#L352-L374
Incorrect share conversions lead to incorrect pricing of assets and loss of principal. aTokens are rebasing tokens, which means that holders of the token have their `balanceof()` increase over time, but each token is still redeemable for exactly one underlying asset. Any formula that does not return one out for one in is incorrect. | 6 |
115_PARMinerV2.sol | pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IGenericMinerV2.sol";
import "../../dex/interfaces/IDexAddressProvider.sol";
import "../../interfaces/IVaultsDataProvider.sol";
import "../../libraries/ABDKMath64x64.sol";
import "../../libraries/WadRayMath.sol";
contract PARMinerV2 is IGenericMinerV2 {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using WadRayMath for uint256;
IERC20 internal _par;
IGovernanceAddressProvider internal _a;
IDexAddressProvider internal immutable _dexAP;
BoostConfig internal _boostConfig;
mapping(address => UserInfo) internal _users;
uint256 internal _totalStake;
uint256 internal _totalStakeWithBoost;
uint256 internal _liquidateCallerReward;
uint256 internal _mimoBalanceTracker;
uint256 internal _accMimoAmountPerShare;
uint256 internal _parBalanceTracker;
uint256 internal _accParAmountPerShare;
modifier onlyManager {
require(_a.parallel().controller().hasRole(_a.parallel().controller().MANAGER_ROLE(), msg.sender), "LM010");
_;
}
constructor(
IGovernanceAddressProvider govAP,
IDexAddressProvider dexAP,
BoostConfig memory boostConfig
) public {
require(address(govAP) != address(0), "LM000");
require(address(dexAP) != address(0), "LM000");
require(boostConfig.a >= 1 && boostConfig.d > 0 && boostConfig.maxBoost >= 1, "LM004");
_a = govAP;
_dexAP = dexAP;
_liquidateCallerReward = 200 ether;
_par = IERC20(govAP.parallel().stablex());
_par.approve(address(_a.parallel().core()), uint256(-1));
_boostConfig = boostConfig;
emit BoostConfigSet(boostConfig);
}
function setBoostConfig(BoostConfig memory newBoostConfig) external onlyManager {
require(newBoostConfig.a >= 1 && newBoostConfig.d > 0 && newBoostConfig.maxBoost >= 1, "LM004");
_boostConfig = newBoostConfig;
emit BoostConfigSet(_boostConfig);
}
function setLiquidateCallerReward(uint256 amount) external onlyManager {
_liquidateCallerReward = amount;
}
function deposit(uint256 amount) public {
_par.safeTransferFrom(msg.sender, address(this), amount);
_increaseStake(msg.sender, amount);
}
function withdraw(uint256 amount) public {
_par.safeTransfer(msg.sender, amount);
_decreaseStake(msg.sender, amount);
}
function liquidate(
uint256 vaultId,
uint256 amount,
uint256 dexIndex,
bytes calldata dexTxData
) public {
uint256 parBalanceBefore = _par.balanceOf(address(this));
IVaultsDataProvider.Vault memory vault = _a.parallel().vaultsData().vaults(vaultId);
IERC20 collateralToken = IERC20(vault.collateralType);
_a.parallel().core().liquidatePartial(vaultId, amount);
(address proxy, address router) = _dexAP.dexMapping(dexIndex);
collateralToken.approve(proxy, collateralToken.balanceOf(address(this)));
router.call(dexTxData);
_par.safeTransfer(msg.sender, _liquidateCallerReward);
require(_par.balanceOf(address(this)) > parBalanceBefore, "LM104");
_refreshPAR(_totalStake);
}
function releaseRewards(address _user) public override {
UserInfo memory _userInfo = _users[_user];
_releaseRewards(_user, _userInfo, _totalStake, false);
_userInfo.accAmountPerShare = _accMimoAmountPerShare;
_userInfo.accParAmountPerShare = _accParAmountPerShare;
_updateBoost(_user, _userInfo);
}
function restakePAR(address _user) public {
UserInfo storage userInfo = _users[_user];
_refresh();
_refreshPAR(_totalStake);
uint256 pendingPAR = userInfo.stakeWithBoost.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare));
_parBalanceTracker = _parBalanceTracker.sub(pendingPAR);
userInfo.accParAmountPerShare = _accParAmountPerShare;
_increaseStake(_user, pendingPAR);
}
function updateBoost(address _user) public {
UserInfo memory userInfo = _users[_user];
_updateBoost(_user, userInfo);
}
function stake(address _user) public view override returns (uint256) {
return _users[_user].stake;
}
function stakeWithBoost(address _user) public view override returns (uint256) {
return _users[_user].stakeWithBoost;
}
function pendingMIMO(address _user) public view override returns (uint256) {
UserInfo memory _userInfo = _users[_user];
return _pendingMIMO(_userInfo.stakeWithBoost, _userInfo.accAmountPerShare);
}
function pendingPAR(address _user) public view override returns (uint256) {
UserInfo memory _userInfo = _users[_user];
uint256 currentBalance = _par.balanceOf(address(this)).sub(_totalStake);
uint256 reward = currentBalance.sub(_parBalanceTracker);
uint256 accParAmountPerShare = _accParAmountPerShare.add(reward.rayDiv(_totalStakeWithBoost));
return _pendingPAR(accParAmountPerShare, _userInfo.stakeWithBoost, _userInfo.accParAmountPerShare);
}
function par() public view override returns (IERC20) {
return _par;
}
function a() public view override returns (IGovernanceAddressProvider) {
return _a;
}
function boostConfig() public view override returns (BoostConfig memory) {
return _boostConfig;
}
function totalStake() public view override returns (uint256) {
return _totalStake;
}
function totalStakeWithBoost() public view override returns (uint256) {
return _totalStakeWithBoost;
}
function liquidateCallerReward() public view returns (uint256) {
return _liquidateCallerReward;
}
function userInfo(address _user) public view override returns (UserInfo memory) {
return _users[_user];
}
function _increaseStake(address _user, uint256 _value) internal {
require(_value > 0, "LM101");
UserInfo memory _userInfo = _users[_user];
uint256 newTotalStake = _totalStake.add(_value);
_releaseRewards(_user, _userInfo, newTotalStake, true);
uint256 pendingPAR = _pendingPAR(_accParAmountPerShare, _userInfo.stakeWithBoost, _userInfo.accParAmountPerShare);
_totalStake = newTotalStake;
_userInfo.stake = _userInfo.stake.add(_value);
_userInfo.accAmountPerShare = _accMimoAmountPerShare;
_userInfo.accParAmountPerShare = _accParAmountPerShare;
if (pendingPAR > 0) {
_userInfo.stake = _userInfo.stake.add(pendingPAR);
_totalStake = _totalStake.add(pendingPAR);
}
_updateBoost(_user, _userInfo);
emit StakeIncreased(_user, _value.add(pendingPAR));
}
function _decreaseStake(address _user, uint256 _value) internal {
require(_value > 0, "LM101");
UserInfo memory _userInfo = _users[_user];
require(_userInfo.stake >= _value, "LM102");
uint256 newTotalStake = _totalStake.sub(_value);
_releaseRewards(_user, _userInfo, newTotalStake, false);
_totalStake = newTotalStake;
_userInfo.stake = _userInfo.stake.sub(_value);
_userInfo.accAmountPerShare = _accMimoAmountPerShare;
_userInfo.accParAmountPerShare = _accParAmountPerShare;
_updateBoost(_user, _userInfo);
emit StakeDecreased(_user, _value);
}
function _releaseRewards(
address _user,
UserInfo memory _userInfo,
uint256 _newTotalStake,
bool _restakePAR
) internal {
uint256 pendingMIMO = _pendingMIMO(_userInfo.stakeWithBoost, _userInfo.accAmountPerShare);
_refresh();
_refreshPAR(_newTotalStake);
uint256 pendingPAR = _pendingPAR(_accParAmountPerShare, _userInfo.stakeWithBoost, _userInfo.accParAmountPerShare);
if (_userInfo.stakeWithBoost > 0) {
_mimoBalanceTracker = _mimoBalanceTracker.sub(pendingMIMO);
_parBalanceTracker = _parBalanceTracker.sub(pendingPAR);
}
if (pendingPAR > 0 && !_restakePAR) {
require(_par.transfer(_user, pendingPAR), "LM100");
}
if (pendingMIMO > 0) {
require(_a.mimo().transfer(_user, pendingMIMO), "LM100");
}
}
function _updateBoost(address _user, UserInfo memory _userInfo) internal {
if (_userInfo.stakeWithBoost > 0) {
_totalStakeWithBoost = _totalStakeWithBoost.sub(_userInfo.stakeWithBoost);
}
uint256 multiplier = _getBoostMultiplier(_user);
_userInfo.stakeWithBoost = _userInfo.stake.wadMul(multiplier);
_totalStakeWithBoost = _totalStakeWithBoost.add(_userInfo.stakeWithBoost);
_users[_user] = _userInfo;
}
function _refresh() internal {
if (_totalStake == 0) {
return;
}
uint256 currentMimoBalance = _a.mimo().balanceOf(address(this));
uint256 mimoReward = currentMimoBalance.sub(_mimoBalanceTracker);
_mimoBalanceTracker = currentMimoBalance;
_accMimoAmountPerShare = _accMimoAmountPerShare.add(mimoReward.rayDiv(_totalStakeWithBoost));
}
function _refreshPAR(uint256 newTotalStake) internal {
if (_totalStake == 0) {
return;
}
uint256 currentParBalance = _par.balanceOf(address(this)).sub(newTotalStake);
uint256 parReward = currentParBalance.sub(_parBalanceTracker);
_parBalanceTracker = currentParBalance;
_accParAmountPerShare = _accParAmountPerShare.add(parReward.rayDiv(_totalStakeWithBoost));
}
function _pendingMIMO(uint256 _userStakeWithBoost, uint256 _userAccAmountPerShare) internal view returns (uint256) {
if (_totalStakeWithBoost == 0) {
return 0;
}
uint256 currentBalance = _a.mimo().balanceOf(address(this));
uint256 reward = currentBalance.sub(_mimoBalanceTracker);
uint256 accMimoAmountPerShare = _accMimoAmountPerShare.add(reward.rayDiv(_totalStakeWithBoost));
return _userStakeWithBoost.rayMul(accMimoAmountPerShare.sub(_userAccAmountPerShare));
}
function _pendingPAR(
uint256 accParAmountPerShare,
uint256 _userStakeWithBoost,
uint256 _userAccParAmountPerShare
) internal view returns (uint256) {
if (_totalStakeWithBoost == 0) {
return 0;
}
return _userStakeWithBoost.rayMul(accParAmountPerShare.sub(_userAccParAmountPerShare));
}
function _getBoostMultiplier(address _user) internal view returns (uint256) {
uint256 veMIMO = _a.votingEscrow().balanceOf(_user);
if (veMIMO == 0) return 1e18;
int128 a = ABDKMath64x64.fromUInt(_boostConfig.a);
int128 b = ABDKMath64x64.fromUInt(_boostConfig.b);
int128 c = ABDKMath64x64.fromUInt(_boostConfig.c);
int128 e = ABDKMath64x64.fromUInt(_boostConfig.e);
int128 DECIMALS = ABDKMath64x64.fromUInt(1e18);
int128 e1 = veMIMO.divu(_boostConfig.d);
int128 e2 = e1.sub(e);
int128 e3 = e2.neg();
int128 e4 = e3.exp();
int128 e5 = e4.add(c);
int128 e6 = b.div(e5).add(a);
uint64 e7 = e6.mul(DECIMALS).toUInt();
uint256 multiplier = uint256(e7);
require(multiplier >= 1e18 && multiplier <= _boostConfig.maxBoost, "LM103");
return multiplier;
}
} | 2,923 | 256 | 1 | 1. [H-01] User can call `liquidate()` and steal all collateral due to arbitrary router call (Lack of input validation)
A malicious user is able to steal all collateral of an unhealthy position in PARMinerV2.sol. The code for the `liquidate()` function is written so that the following steps are followed:
The exploit occurs with the arbitrary router call. The malicious user is able to supply the dexTxnData parameter which dictates the function `router.call(dexTxData)` to the router. If the user supplied a function such as UniswapV2Router's `swapExactTokenForETH()`, then control flow will be given to the user, allowing them to perform the exploit.
2. [M-02] Users can use `updateBoost()` function to claim unfairly large rewards from liquidity mining contracts for themselves at cost of other users. (Lack of access control)
Users aware of this vulnerability could effectively steal a portion of liquidity mining rewards from honest users.
| 2 |
115_SuperVault.sol | pragma experimental ABIEncoderV2;
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import { IPool } from "@aave/core-v3/contracts/interfaces/IPool.sol";
import "./interfaces/IAddressProvider.sol";
import "./interfaces/IGovernanceAddressProvider.sol";
import "./interfaces/IVaultsCore.sol";
import "./interfaces/IGenericMiner.sol";
import "./interfaces/IDexAddressProvider.sol";
contract SuperVault is AccessControl, Initializable {
enum Operation {
LEVERAGE,
REBALANCE,
EMPTY
}
struct AggregatorRequest {
uint256 parToSell;
bytes dexTxData;
uint dexIndex;
}
IAddressProvider public a;
IGovernanceAddressProvider public ga;
IPool public lendingPool;
IDexAddressProvider internal _dexAP;
modifier onlyOwner() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "SV001");
_;
}
function initialize(
IAddressProvider _a,
IGovernanceAddressProvider _ga,
IPool _lendingPool,
address _owner,
IDexAddressProvider dexAP
) external initializer {
require(address(_a) != address(0));
require(address(_ga) != address(0));
require(address(_lendingPool) != address(0));
require(address(dexAP) != address(0));
a = _a;
ga = _ga;
lendingPool = _lendingPool;
_dexAP = dexAP;
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
}
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address,
bytes calldata params
) external returns (bool) {
require(msg.sender == address(lendingPool), "SV002");
(Operation operation, bytes memory operationParams) = abi.decode(params, (Operation, bytes));
IERC20 asset = IERC20(assets[0]);
uint256 flashloanRepayAmount = amounts[0] + premiums[0];
if (operation == Operation.LEVERAGE) {
leverageOperation(asset, flashloanRepayAmount, operationParams);
}
if (operation == Operation.REBALANCE) {
rebalanceOperation(asset, amounts[0], flashloanRepayAmount, operationParams);
}
if (operation == Operation.EMPTY) {
emptyVaultOperation(asset, amounts[0], flashloanRepayAmount, operationParams);
}
asset.approve(address(lendingPool), flashloanRepayAmount);
return true;
}
function leverageOperation(
IERC20 token,
uint256 flashloanRepayAmount,
bytes memory params
) internal {
leverageSwap(params, token);
require(token.balanceOf(address(this)) >= flashloanRepayAmount, "SV101");
a.core().deposit(address(token), token.balanceOf(address(this)) - flashloanRepayAmount);
}
function leverage(
address asset,
uint256 depositAmount,
uint256 borrowAmount,
uint256 parToSell,
bytes calldata dexTxData,
uint dexIndex
) external onlyOwner {
IERC20(asset).transferFrom(msg.sender, address(this), depositAmount);
bytes memory leverageParams = abi.encode(parToSell, dexTxData, dexIndex);
bytes memory params = abi.encode(Operation.LEVERAGE, leverageParams);
takeFlashLoan(asset, borrowAmount, params);
checkAndSendMIMO();
}
function rebalanceOperation(
IERC20 fromCollateral,
uint256 amount,
uint256 flashloanRepayAmount,
bytes memory params
) internal {
(uint256 vaultId, address toCollateral, uint256 parAmount, bytes memory dexTxData, uint dexIndex) = abi
.decode(params, (uint256, address, uint256, bytes, uint ));
aggregatorSwap(dexIndex, fromCollateral, amount, dexTxData);
uint256 depositAmount = IERC20(toCollateral).balanceOf(address(this));
IERC20(toCollateral).approve(address(a.core()), depositAmount);
a.core().depositAndBorrow(toCollateral, depositAmount, parAmount);
a.core().repay(vaultId, parAmount);
a.core().withdraw(vaultId, flashloanRepayAmount);
require(fromCollateral.balanceOf(address(this)) >= flashloanRepayAmount, "SV101");
}
function rebalance(
uint256 vaultId,
address toCollateral,
address fromCollateral,
uint256 fromCollateralAmount,
uint256 parAmount,
bytes calldata dexTxData,
uint dexIndex
) external onlyOwner {
bytes memory rebalanceParams = abi.encode(vaultId, toCollateral, parAmount, dexTxData, dexIndex);
bytes memory params = abi.encode(Operation.REBALANCE, rebalanceParams);
takeFlashLoan(fromCollateral, fromCollateralAmount, params);
checkAndSendMIMO();
}
function emptyVaultOperation(
IERC20 vaultCollateral,
uint256 amount,
uint256 flashloanRepayAmount,
bytes memory params
) internal {
(uint256 vaultId, bytes memory dexTxData, uint dexIndex) = abi.decode(params, (uint256, bytes, uint));
aggregatorSwap(dexIndex, vaultCollateral, amount, dexTxData);
IERC20 par = IERC20(a.stablex());
par.approve(address(a.core()), par.balanceOf(address(this)));
a.core().repayAll(vaultId);
uint256 vaultBalance = a.vaultsData().vaultCollateralBalance(vaultId);
a.core().withdraw(vaultId, vaultBalance);
require(vaultCollateral.balanceOf(address(this)) >= flashloanRepayAmount, "SV101");
}
function emptyVault(
uint256 vaultId,
address collateralType,
uint256 repayAmount,
bytes calldata dexTxData,
uint dexIndex
) external onlyOwner {
bytes memory emptyVaultParams = abi.encode(vaultId, dexTxData, dexIndex);
bytes memory params = abi.encode(Operation.EMPTY, emptyVaultParams);
takeFlashLoan(collateralType, repayAmount, params);
checkAndSendMIMO();
require(IERC20(a.stablex()).transfer(msg.sender, IERC20(a.stablex()).balanceOf(address(this))));
checkAndSendMIMO();
IERC20 collateral = IERC20(collateralType);
collateral.transfer(msg.sender, collateral.balanceOf(address(this)));
}
function withdrawFromVault(uint256 vaultId, uint256 amount) external onlyOwner {
a.core().withdraw(vaultId, amount);
IERC20 asset = IERC20(a.vaultsData().vaultCollateralType(vaultId));
require(asset.transfer(msg.sender, amount));
}
function borrowFromVault(uint256 vaultId, uint256 amount) external onlyOwner {
a.core().borrow(vaultId, amount);
require(IERC20(a.stablex()).transfer(msg.sender, IERC20(a.stablex()).balanceOf(address(this))));
checkAndSendMIMO();
}
function withdrawAsset(address asset) external onlyOwner {
IERC20 token = IERC20(asset);
require(token.transfer(msg.sender, token.balanceOf(address(this))));
}
function depositToVault(address asset, uint256 amount) external {
IERC20 token = IERC20(asset);
token.approve(address(a.core()), amount);
token.transferFrom(msg.sender, address(this), amount);
a.core().deposit(asset, amount);
}
function depositAndBorrowFromVault(
address asset,
uint256 depositAmount,
uint256 borrowAmount
) external onlyOwner {
IERC20 token = IERC20(asset);
token.approve(address(a.core()), depositAmount);
token.transferFrom(msg.sender, address(this), depositAmount);
a.core().depositAndBorrow(asset, depositAmount, borrowAmount);
require(IERC20(a.stablex()).transfer(msg.sender, IERC20(a.stablex()).balanceOf(address(this))));
checkAndSendMIMO();
}
function releaseMIMO(address minerAddress) external payable onlyOwner {
IGenericMiner miner = IGenericMiner(minerAddress);
miner.releaseMIMO(address(this));
checkAndSendMIMO();
}
function depositETHToVault() external payable {
a.core().depositETH{ value: msg.value }();
}
function depositETHAndBorrowFromVault(uint256 borrowAmount) external payable onlyOwner {
a.core().depositETHAndBorrow{ value: msg.value }(borrowAmount);
require(IERC20(a.stablex()).transfer(msg.sender, IERC20(a.stablex()).balanceOf(address(this))));
checkAndSendMIMO();
}
function leverageSwap(bytes memory params, IERC20 token) internal {
(uint256 parToSell, bytes memory dexTxData, uint dexIndex) = abi.decode(
params,
(uint256, bytes, uint )
);
token.approve(address(a.core()), 2**256 - 1);
a.core().depositAndBorrow(address(token), token.balanceOf(address(this)), parToSell);
IERC20 par = IERC20(a.stablex());
aggregatorSwap(dexIndex, par, parToSell, dexTxData);
}
function aggregatorSwap(
uint256 dexIndex,
IERC20 token,
uint256 amount,
bytes memory dexTxData
) internal {
(address proxy, address router) = _dexAP.dexMapping(dexIndex);
require(proxy != address(0) && router != address(0), "SV201");
token.approve(proxy, amount);
router.call(dexTxData);
}
function takeFlashLoan(
address asset,
uint256 amount,
bytes memory params
) internal {
uint8 referralCode;
address[] memory assets = new address[](1);
uint256[] memory amounts = new uint256[](1);
uint256[] memory modes = new uint256[](1);
(assets[0], amounts[0]) = (asset, amount);
lendingPool.flashLoan(address(this), assets, amounts, modes, address(this), params, referralCode);
}
function checkAndSendMIMO() internal {
if (ga.mimo().balanceOf(address(this)) > 0) {
require(ga.mimo().transfer(msg.sender, ga.mimo().balanceOf(address(this))));
}
}
} | 2,313 | 239 | 0 | 1. [M-03] SuperVault's leverageSwap and emptyVaultOperation can become stuck (Both functions stuck)
`leverageSwap` and `emptyVaultOperation` can be run repeatedly for the same tokens. If these tokens happen to be an ERC20 that do not allow for approval of positive amount when allowance already positive, both functions can become stuck.
2. [M-04] Non-standard ERC20 Tokens are Not Supported
When trying to call function `SuperVault.executeOperation()` the transaction reverts. This is because the call to `asset.approve()` in line{97} doesn't match the expected function signature of approve() on the target contract like in the case of USDT.
| 2 |
94_NFTMarketCreators.sol | pragma solidity ^0.8.0;
import "./OZ/ERC165Checker.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./Constants.sol";
import "../interfaces/IGetFees.sol";
import "../interfaces/IGetRoyalties.sol";
import "../interfaces/IOwnable.sol";
import "../interfaces/IRoyaltyInfo.sol";
import "../interfaces/ITokenCreator.sol";
import "@manifoldxyz/royalty-registry-solidity/contracts/IRoyaltyRegistry.sol";
error NFTMarketCreators_Address_Does_Not_Support_IRoyaltyRegistry();
abstract contract NFTMarketCreators is
Constants,
ReentrancyGuardUpgradeable
{
using ERC165Checker for address;
IRoyaltyRegistry private immutable royaltyRegistry;
constructor(address _royaltyRegistry) {
if (!_royaltyRegistry.supportsInterface(type(IRoyaltyRegistry).interfaceId)) {
revert NFTMarketCreators_Address_Does_Not_Support_IRoyaltyRegistry();
}
royaltyRegistry = IRoyaltyRegistry(_royaltyRegistry);
}
function _getCreatorPaymentInfo(
address nftContract,
uint256 tokenId,
address seller
)
internal
view
returns (
address payable[] memory recipients,
uint256[] memory splitPerRecipientInBasisPoints,
bool isCreator
)
{
if (nftContract.supportsERC165Interface(type(IRoyaltyInfo).interfaceId)) {
try IRoyaltyInfo(nftContract).royaltyInfo{ gas: READ_ONLY_GAS_LIMIT }(tokenId, BASIS_POINTS) returns (
address receiver,
) {
if (receiver != address(0)) {
recipients = new address payable[](1);
recipients[0] = payable(receiver);
if (receiver == seller) {
return (recipients, splitPerRecipientInBasisPoints, true);
}
}
} catch
{
}
}
if (recipients.length == 0 && nftContract.supportsERC165Interface(type(IGetRoyalties).interfaceId)) {
try IGetRoyalties(nftContract).getRoyalties{ gas: READ_ONLY_GAS_LIMIT }(tokenId) returns (
address payable[] memory _recipients,
uint256[] memory recipientBasisPoints
) {
if (_recipients.length > 0 && _recipients.length == recipientBasisPoints.length) {
bool hasRecipient;
unchecked {
for (uint256 i = 0; i < _recipients.length; ++i) {
if (_recipients[i] != address(0)) {
hasRecipient = true;
if (_recipients[i] == seller) {
return (_recipients, recipientBasisPoints, true);
}
}
}
}
if (hasRecipient) {
recipients = _recipients;
splitPerRecipientInBasisPoints = recipientBasisPoints;
}
}
} catch
{
}
}
if (recipients.length == 0) {
try royaltyRegistry.getRoyaltyLookupAddress{ gas: READ_ONLY_GAS_LIMIT }(nftContract) returns (
address overrideContract
) {
if (overrideContract != nftContract) {
nftContract = overrideContract;
if (nftContract.supportsERC165Interface(type(IRoyaltyInfo).interfaceId)) {
try IRoyaltyInfo(nftContract).royaltyInfo{ gas: READ_ONLY_GAS_LIMIT }(tokenId, BASIS_POINTS) returns (
address receiver,
) {
if (receiver != address(0)) {
recipients = new address payable[](1);
recipients[0] = payable(receiver);
if (receiver == seller) {
return (recipients, splitPerRecipientInBasisPoints, true);
}
}
} catch
{
}
}
if (recipients.length == 0 && nftContract.supportsERC165Interface(type(IGetRoyalties).interfaceId)) {
try IGetRoyalties(nftContract).getRoyalties{ gas: READ_ONLY_GAS_LIMIT }(tokenId) returns (
address payable[] memory _recipients,
uint256[] memory recipientBasisPoints
) {
if (_recipients.length > 0 && _recipients.length == recipientBasisPoints.length) {
bool hasRecipient;
for (uint256 i = 0; i < _recipients.length; ++i) {
if (_recipients[i] != address(0)) {
hasRecipient = true;
if (_recipients[i] == seller) {
return (_recipients, recipientBasisPoints, true);
}
}
}
if (hasRecipient) {
recipients = _recipients;
splitPerRecipientInBasisPoints = recipientBasisPoints;
}
}
} catch
{
}
}
}
} catch
{
}
}
if (recipients.length == 0 && nftContract.supportsERC165Interface(type(IGetFees).interfaceId)) {
try IGetFees(nftContract).getFeeRecipients{ gas: READ_ONLY_GAS_LIMIT }(tokenId) returns (
address payable[] memory _recipients
) {
if (_recipients.length > 0) {
try IGetFees(nftContract).getFeeBps{ gas: READ_ONLY_GAS_LIMIT }(tokenId) returns (
uint256[] memory recipientBasisPoints
) {
if (_recipients.length == recipientBasisPoints.length) {
bool hasRecipient;
unchecked {
for (uint256 i = 0; i < _recipients.length; ++i) {
if (_recipients[i] != address(0)) {
hasRecipient = true;
if (_recipients[i] == seller) {
return (_recipients, recipientBasisPoints, true);
}
}
}
}
if (hasRecipient) {
recipients = _recipients;
splitPerRecipientInBasisPoints = recipientBasisPoints;
}
}
} catch
{
}
}
} catch
{
}
}
try ITokenCreator(nftContract).tokenCreator{ gas: READ_ONLY_GAS_LIMIT }(tokenId) returns (
address payable _creator
) {
if (_creator != address(0)) {
if (recipients.length == 0) {
recipients = new address payable[](1);
recipients[0] = _creator;
}
return (recipients, splitPerRecipientInBasisPoints, _creator == seller);
}
} catch
{
}
try IOwnable(nftContract).owner{ gas: READ_ONLY_GAS_LIMIT }() returns (address owner) {
if (recipients.length == 0) {
recipients = new address payable[](1);
recipients[0] = payable(owner);
}
return (recipients, splitPerRecipientInBasisPoints, owner == seller);
} catch
{
}
}
function getRoyaltyRegistry() public view returns (address registry) {
return address(royaltyRegistry);
}
uint256[500] private __gap;
} | 1,528 | 188 | 0 | 1. [H-02] Creators can steal sale revenue from owners' sales (Centralization Risks, Unchecked Length Mismatches)
`_recipients[i] == seller` in `_getCreatorPaymentInfo` function
Using the Royalty Registry an owner can decide to change the royalty information right before the sale is complete, affecting who gets what.
2. [M-07] `_getCreatorPaymentInfo()` is Not Equipped to Handle Reverts on an Unbounded _recipients Array (Unchecked loops)
The `_getCreatorPaymentInfo()` function is utilised by _distributeFunds() whenever an NFT sale is made. The function uses try and catch statements to handle bad API endpoints.
| 2 |
94_FETH.sol | pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./libraries/LockedBalance.sol";
error FETH_Cannot_Deposit_For_Lockup_With_Address_Zero();
error FETH_Escrow_Expired();
error FETH_Escrow_Not_Found();
error FETH_Expiration_Too_Far_In_Future();
error FETH_Insufficient_Allowance(uint256 amount);
error FETH_Insufficient_Available_Funds(uint256 amount);
error FETH_Insufficient_Escrow(uint256 amount);
error FETH_Invalid_Lockup_Duration();
error FETH_Market_Must_Be_A_Contract();
error FETH_Must_Deposit_Non_Zero_Amount();
error FETH_Must_Lockup_Non_Zero_Amount();
error FETH_No_Funds_To_Withdraw();
error FETH_Only_FND_Market_Allowed();
error FETH_Too_Much_ETH_Provided();
error FETH_Transfer_To_Burn_Not_Allowed();
error FETH_Transfer_To_FETH_Not_Allowed();
contract FETH {
using AddressUpgradeable for address payable;
using LockedBalance for LockedBalance.Lockups;
using Math for uint256;
struct AccountInfo {
uint96 freedBalance;
uint32 lockupStartIndex;
LockedBalance.Lockups lockups;
mapping(address => uint256) allowance;
}
mapping(address => AccountInfo) private accountToInfo;
uint256 private immutable lockupDuration;
uint256 private immutable lockupInterval;
address payable private immutable foundationMarket;
uint8 public constant decimals = 18;
string public constant name = "Foundation Wrapped Ether";
string public constant symbol = "FETH";
event Approval(address indexed from, address indexed spender, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 amount);
event BalanceLocked(address indexed account, uint256 indexed expiration, uint256 amount, uint256 valueDeposited);
event BalanceUnlocked(address indexed account, uint256 indexed expiration, uint256 amount);
event ETHWithdrawn(address indexed from, address indexed to, uint256 amount);
modifier onlyFoundationMarket() {
if (msg.sender != foundationMarket) {
revert FETH_Only_FND_Market_Allowed();
}
_;
}
constructor(address payable _foundationMarket, uint256 _lockupDuration) {
if (!_foundationMarket.isContract()) {
revert FETH_Market_Must_Be_A_Contract();
}
foundationMarket = _foundationMarket;
lockupDuration = _lockupDuration;
lockupInterval = _lockupDuration / 24;
if (lockupInterval * 24 != _lockupDuration || _lockupDuration == 0) {
revert FETH_Invalid_Lockup_Duration();
}
}
receive() external payable {
depositFor(msg.sender);
}
function approve(address spender, uint256 amount) external returns (bool success) {
accountToInfo[msg.sender].allowance[spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function deposit() external payable {
depositFor(msg.sender);
}
function depositFor(address account) public payable {
if (msg.value == 0) {
revert FETH_Must_Deposit_Non_Zero_Amount();
}
AccountInfo storage accountInfo = accountToInfo[account];
unchecked {
accountInfo.freedBalance += uint96(msg.value);
}
emit Transfer(address(0), account, msg.value);
}
function marketChangeLockup(
address unlockFrom,
uint256 unlockExpiration,
uint256 unlockAmount,
address lockupFor,
uint256 lockupAmount
) external payable onlyFoundationMarket returns (uint256 expiration) {
_marketUnlockFor(unlockFrom, unlockExpiration, unlockAmount);
return _marketLockupFor(lockupFor, lockupAmount);
}
function marketLockupFor(address account, uint256 amount)
external
payable
onlyFoundationMarket
returns (uint256 expiration)
{
return _marketLockupFor(account, amount);
}
function marketUnlockFor(
address account,
uint256 expiration,
uint256 amount
) external onlyFoundationMarket {
_marketUnlockFor(account, expiration, amount);
}
function marketWithdrawFrom(address from, uint256 amount) external onlyFoundationMarket {
AccountInfo storage accountInfo = _freeFromEscrow(from);
_deductBalanceFrom(accountInfo, amount);
payable(msg.sender).sendValue(amount);
emit ETHWithdrawn(from, msg.sender, amount);
}
function marketWithdrawLocked(
address account,
uint256 expiration,
uint256 amount
) external onlyFoundationMarket {
_removeFromLockedBalance(account, expiration, amount);
payable(msg.sender).sendValue(amount);
emit ETHWithdrawn(account, msg.sender, amount);
}
function transfer(address to, uint256 amount) external returns (bool success) {
return transferFrom(msg.sender, to, amount);
}
function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool success) {
if (to == address(0)) {
revert FETH_Transfer_To_Burn_Not_Allowed();
} else if (to == address(this)) {
revert FETH_Transfer_To_FETH_Not_Allowed();
}
AccountInfo storage fromAccountInfo = _freeFromEscrow(from);
if (from != msg.sender) {
_deductAllowanceFrom(fromAccountInfo, amount);
}
_deductBalanceFrom(fromAccountInfo, amount);
AccountInfo storage toAccountInfo = accountToInfo[to];
unchecked {
toAccountInfo.freedBalance += uint96(amount);
}
emit Transfer(from, to, amount);
return true;
}
function withdrawAvailableBalance() external {
AccountInfo storage accountInfo = _freeFromEscrow(msg.sender);
uint256 amount = accountInfo.freedBalance;
if (amount == 0) {
revert FETH_No_Funds_To_Withdraw();
}
delete accountInfo.freedBalance;
payable(msg.sender).sendValue(amount);
emit ETHWithdrawn(msg.sender, msg.sender, amount);
}
function withdrawFrom(
address from,
address payable to,
uint256 amount
) external {
if (amount == 0) {
revert FETH_No_Funds_To_Withdraw();
}
AccountInfo storage accountInfo = _freeFromEscrow(from);
if (from != msg.sender) {
_deductAllowanceFrom(accountInfo, amount);
}
_deductBalanceFrom(accountInfo, amount);
to.sendValue(amount);
emit ETHWithdrawn(from, to, amount);
}
function _deductAllowanceFrom(AccountInfo storage accountInfo, uint256 amount) private {
if (accountInfo.allowance[msg.sender] != type(uint256).max) {
if (accountInfo.allowance[msg.sender] < amount) {
revert FETH_Insufficient_Allowance(accountInfo.allowance[msg.sender]);
}
unchecked {
accountInfo.allowance[msg.sender] -= amount;
}
}
}
function _deductBalanceFrom(AccountInfo storage accountInfo, uint256 amount) private {
if (accountInfo.freedBalance < amount) {
revert FETH_Insufficient_Available_Funds(accountInfo.freedBalance);
}
unchecked {
accountInfo.freedBalance -= uint96(amount);
}
}
function _freeFromEscrow(address account) private returns (AccountInfo storage) {
AccountInfo storage accountInfo = accountToInfo[account];
uint256 escrowIndex = accountInfo.lockupStartIndex;
LockedBalance.Lockup memory escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == 0 || escrow.expiration >= block.timestamp) {
return accountInfo;
}
while (true) {
unchecked {
accountInfo.freedBalance += escrow.totalAmount;
accountInfo.lockups.del(escrowIndex);
escrow = accountInfo.lockups.get(escrowIndex + 1);
}
if (escrow.expiration == 0) {
break;
}
unchecked {
++escrowIndex;
}
if (escrow.expiration >= block.timestamp) {
break;
}
}
unchecked {
accountInfo.lockupStartIndex = uint32(escrowIndex);
}
return accountInfo;
}
function _marketLockupFor(address account, uint256 amount) private returns (uint256 expiration) {
if (account == address(0)) {
revert FETH_Cannot_Deposit_For_Lockup_With_Address_Zero();
}
if (amount == 0) {
revert FETH_Must_Lockup_Non_Zero_Amount();
}
unchecked {
expiration = lockupDuration + block.timestamp.ceilDiv(lockupInterval) * lockupInterval;
}
AccountInfo storage accountInfo = _freeFromEscrow(account);
if (msg.value < amount) {
unchecked {
uint256 delta = amount - msg.value;
if (accountInfo.freedBalance < delta) {
revert FETH_Insufficient_Available_Funds(accountInfo.freedBalance);
}
accountInfo.freedBalance -= uint96(delta);
}
} else if (msg.value != amount) {
revert FETH_Too_Much_ETH_Provided();
}
unchecked {
for (uint256 escrowIndex = accountInfo.lockupStartIndex; ; ++escrowIndex) {
LockedBalance.Lockup memory escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == 0) {
if (expiration > type(uint32).max) {
revert FETH_Expiration_Too_Far_In_Future();
}
accountInfo.lockups.set(escrowIndex, expiration, amount);
break;
}
if (escrow.expiration == expiration) {
accountInfo.lockups.setTotalAmount(escrowIndex, escrow.totalAmount + amount);
break;
}
}
}
emit BalanceLocked(account, expiration, amount, msg.value);
}
function _marketUnlockFor(
address account,
uint256 expiration,
uint256 amount
) private {
AccountInfo storage accountInfo = _removeFromLockedBalance(account, expiration, amount);
unchecked {
accountInfo.freedBalance += uint96(amount);
}
}
function _removeFromLockedBalance(
address account,
uint256 expiration,
uint256 amount
) private returns (AccountInfo storage) {
if (expiration < block.timestamp) {
revert FETH_Escrow_Expired();
}
AccountInfo storage accountInfo = accountToInfo[account];
uint256 escrowIndex = accountInfo.lockupStartIndex;
LockedBalance.Lockup memory escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == expiration) {
if (escrow.totalAmount == amount) {
accountInfo.lockups.del(escrowIndex);
if (accountInfo.lockups.get(escrowIndex + 1).expiration != 0) {
unchecked {
++accountInfo.lockupStartIndex;
}
}
} else {
if (escrow.totalAmount < amount) {
revert FETH_Insufficient_Escrow(escrow.totalAmount);
}
unchecked {
accountInfo.lockups.setTotalAmount(escrowIndex, escrow.totalAmount - amount);
}
}
} else {
while (true) {
unchecked {
++escrowIndex;
}
escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == expiration) {
if (amount > escrow.totalAmount) {
revert FETH_Insufficient_Escrow(escrow.totalAmount);
}
unchecked {
accountInfo.lockups.setTotalAmount(escrowIndex, escrow.totalAmount - amount);
}
break;
}
if (escrow.expiration == 0) {
revert FETH_Escrow_Not_Found();
}
}
}
emit BalanceUnlocked(account, expiration, amount);
return accountInfo;
}
function allowance(address account, address operator) external view returns (uint256 amount) {
AccountInfo storage accountInfo = accountToInfo[account];
return accountInfo.allowance[operator];
}
function balanceOf(address account) external view returns (uint256 balance) {
AccountInfo storage accountInfo = accountToInfo[account];
balance = accountInfo.freedBalance;
unchecked {
for (uint256 escrowIndex = accountInfo.lockupStartIndex; ; ++escrowIndex) {
LockedBalance.Lockup memory escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == 0 || escrow.expiration >= block.timestamp) {
break;
}
balance += escrow.totalAmount;
}
}
}
function getFoundationMarket() external view returns (address market) {
return foundationMarket;
}
function getLockups(address account) external view returns (uint256[] memory expiries, uint256[] memory amounts) {
AccountInfo storage accountInfo = accountToInfo[account];
uint256 lockedCount;
unchecked {
for (uint256 escrowIndex = accountInfo.lockupStartIndex; ; ++escrowIndex) {
LockedBalance.Lockup memory escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == 0) {
break;
}
if (escrow.expiration >= block.timestamp && escrow.totalAmount > 0) {
++lockedCount;
}
}
}
expiries = new uint256[](lockedCount);
amounts = new uint256[](lockedCount);
uint256 i;
unchecked {
for (uint256 escrowIndex = accountInfo.lockupStartIndex; ; ++escrowIndex) {
LockedBalance.Lockup memory escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == 0) {
break;
}
if (escrow.expiration >= block.timestamp && escrow.totalAmount > 0) {
expiries[i] = escrow.expiration;
amounts[i] = escrow.totalAmount;
++i;
}
}
}
}
function totalBalanceOf(address account) external view returns (uint256 balance) {
AccountInfo storage accountInfo = accountToInfo[account];
balance = accountInfo.freedBalance;
unchecked {
for (uint256 escrowIndex = accountInfo.lockupStartIndex; ; ++escrowIndex) {
LockedBalance.Lockup memory escrow = accountInfo.lockups.get(escrowIndex);
if (escrow.expiration == 0) {
break;
}
balance += escrow.totalAmount;
}
}
}
function totalSupply() external view returns (uint256 supply) {
return address(this).balance;
}
} | 3,266 | 385 | 1 | 1. [M-03] Approve race condition in FETH (Front-running)
in `approve` function
2. [M-09] Missing receiver validation in `withdrawFrom()` (No check address, Lack of Input Validation)
The FETH.withdrawFrom function does not validate its to parameter. | 2 |
97_LiquidityFarming.sol | pragma solidity 0.8.0;
import "@openzeppelin/contracts-upgradeable/interfaces/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./metatx/ERC2771ContextUpgradeable.sol";
import "../security/Pausable.sol";
import "./interfaces/ILPToken.sol";
import "./interfaces/ILiquidityProviders.sol";
contract HyphenLiquidityFarming is
Initializable,
ERC2771ContextUpgradeable,
OwnableUpgradeable,
Pausable,
ReentrancyGuardUpgradeable,
IERC721ReceiverUpgradeable
{
using SafeERC20Upgradeable for IERC20Upgradeable;
ILPToken public lpToken;
ILiquidityProviders public liquidityProviders;
struct NFTInfo {
address payable staker;
uint256 rewardDebt;
uint256 unpaidRewards;
bool isStaked;
}
struct PoolInfo {
uint256 accTokenPerShare;
uint256 lastRewardTime;
}
struct RewardsPerSecondEntry {
uint256 rewardsPerSecond;
uint256 timestamp;
}
mapping(address => PoolInfo) public poolInfo;
mapping(uint256 => NFTInfo) public nftInfo;
mapping(address => address) public rewardTokens;
mapping(address => uint256[]) public nftIdsStaked;
mapping(address => uint256) public totalSharesStaked;
mapping(address => RewardsPerSecondEntry[]) public rewardRateLog;
uint256 private constant ACC_TOKEN_PRECISION = 1e12;
address internal constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
event LogDeposit(address indexed user, address indexed baseToken, uint256 nftId);
event LogWithdraw(address indexed user, address baseToken, uint256 nftId, address indexed to);
event LogOnReward(address indexed user, address indexed baseToken, uint256 amount, address indexed to);
event LogUpdatePool(address indexed baseToken, uint256 lastRewardTime, uint256 lpSupply, uint256 accToken1PerShare);
event LogRewardPerSecond(address indexed baseToken, uint256 rewardPerSecond);
event LogRewardPoolInitialized(address _baseToken, address _rewardToken, uint256 _rewardPerSecond);
event LogNativeReceived(address indexed sender, uint256 value);
function initialize(
address _trustedForwarder,
address _pauser,
ILiquidityProviders _liquidityProviders,
ILPToken _lpToken
) public initializer {
__ERC2771Context_init(_trustedForwarder);
__Ownable_init();
__Pausable_init(_pauser);
__ReentrancyGuard_init();
liquidityProviders = _liquidityProviders;
lpToken = _lpToken;
}
function initalizeRewardPool(
address _baseToken,
address _rewardToken,
uint256 _rewardPerSecond
) external onlyOwner {
require(rewardTokens[_baseToken] == address(0), "ERR__POOL_ALREADY_INITIALIZED");
require(_baseToken != address(0), "ERR__BASE_TOKEN_IS_ZERO");
require(_rewardToken != address(0), "ERR_REWARD_TOKEN_IS_ZERO");
rewardTokens[_baseToken] = _rewardToken;
rewardRateLog[_baseToken].push(RewardsPerSecondEntry(_rewardPerSecond, block.timestamp));
emit LogRewardPoolInitialized(_baseToken, _rewardToken, _rewardPerSecond);
}
function _sendErc20AndGetSentAmount(
IERC20Upgradeable _token,
uint256 _amount,
address _to
) private returns (uint256) {
uint256 recepientBalance = _token.balanceOf(_to);
_token.safeTransfer(_to, _amount);
return _token.balanceOf(_to) - recepientBalance;
}
function _sendRewardsForNft(uint256 _nftId, address payable _to) internal {
NFTInfo storage nft = nftInfo[_nftId];
require(nft.isStaked, "ERR__NFT_NOT_STAKED");
(address baseToken, , uint256 amount) = lpToken.tokenMetadata(_nftId);
amount /= liquidityProviders.BASE_DIVISOR();
PoolInfo memory pool = updatePool(baseToken);
uint256 pending;
uint256 amountSent;
if (amount > 0) {
pending = ((amount * pool.accTokenPerShare) / ACC_TOKEN_PRECISION) - nft.rewardDebt + nft.unpaidRewards;
if (rewardTokens[baseToken] == NATIVE) {
uint256 balance = address(this).balance;
if (pending > balance) {
unchecked {
nft.unpaidRewards = pending - balance;
}
(bool success, ) = _to.call{value: balance}("");
require(success, "ERR__NATIVE_TRANSFER_FAILED");
amountSent = balance;
} else {
nft.unpaidRewards = 0;
(bool success, ) = _to.call{value: pending}("");
require(success, "ERR__NATIVE_TRANSFER_FAILED");
amountSent = pending;
}
} else {
IERC20Upgradeable rewardToken = IERC20Upgradeable(rewardTokens[baseToken]);
uint256 balance = rewardToken.balanceOf(address(this));
if (pending > balance) {
unchecked {
nft.unpaidRewards = pending - balance;
}
amountSent = _sendErc20AndGetSentAmount(rewardToken, balance, _to);
} else {
nft.unpaidRewards = 0;
amountSent = _sendErc20AndGetSentAmount(rewardToken, pending, _to);
}
}
}
nft.rewardDebt = (amount * pool.accTokenPerShare) / ACC_TOKEN_PRECISION;
emit LogOnReward(_msgSender(), baseToken, amountSent, _to);
}
function setRewardPerSecond(address _baseToken, uint256 _rewardPerSecond) public onlyOwner {
rewardRateLog[_baseToken].push(RewardsPerSecondEntry(_rewardPerSecond, block.timestamp));
emit LogRewardPerSecond(_baseToken, _rewardPerSecond);
}
function reclaimTokens(
address _token,
uint256 _amount,
address payable _to
) external nonReentrant onlyOwner {
require(_to != address(0), "ERR__TO_IS_ZERO");
if (_token == NATIVE) {
(bool success, ) = payable(_to).call{value: _amount}("");
require(success, "ERR__NATIVE_TRANSFER_FAILED");
} else {
IERC20Upgradeable(_token).safeTransfer(_to, _amount);
}
}
function deposit(uint256 _nftId, address payable _to) external whenNotPaused nonReentrant {
address msgSender = _msgSender();
require(
lpToken.isApprovedForAll(msgSender, address(this)) || lpToken.getApproved(_nftId) == address(this),
"ERR__NOT_APPROVED"
);
(address baseToken, , uint256 amount) = lpToken.tokenMetadata(_nftId);
amount /= liquidityProviders.BASE_DIVISOR();
require(rewardTokens[baseToken] != address(0), "ERR__POOL_NOT_INITIALIZED");
require(rewardRateLog[baseToken].length != 0, "ERR__POOL_NOT_INITIALIZED");
NFTInfo storage nft = nftInfo[_nftId];
require(!nft.isStaked, "ERR__NFT_ALREADY_STAKED");
lpToken.safeTransferFrom(msgSender, address(this), _nftId);
PoolInfo memory pool = updatePool(baseToken);
nft.isStaked = true;
nft.staker = _to;
nft.rewardDebt = (amount * pool.accTokenPerShare) / ACC_TOKEN_PRECISION;
nftIdsStaked[_to].push(_nftId);
totalSharesStaked[baseToken] += amount;
emit LogDeposit(msgSender, baseToken, _nftId);
}
function withdraw(uint256 _nftId, address payable _to) external whenNotPaused nonReentrant {
address msgSender = _msgSender();
uint256 nftsStakedLength = nftIdsStaked[msgSender].length;
uint256 index;
for (index = 0; index < nftsStakedLength; ++index) {
if (nftIdsStaked[msgSender][index] == _nftId) {
break;
}
}
require(index != nftsStakedLength, "ERR__NFT_NOT_STAKED");
nftIdsStaked[msgSender][index] = nftIdsStaked[msgSender][nftIdsStaked[msgSender].length - 1];
nftIdsStaked[msgSender].pop();
_sendRewardsForNft(_nftId, _to);
delete nftInfo[_nftId];
(address baseToken, , uint256 amount) = lpToken.tokenMetadata(_nftId);
amount /= liquidityProviders.BASE_DIVISOR();
totalSharesStaked[baseToken] -= amount;
lpToken.safeTransferFrom(address(this), msgSender, _nftId);
emit LogWithdraw(msgSender, baseToken, _nftId, _to);
}
function extractRewards(uint256 _nftId, address payable _to) external whenNotPaused nonReentrant {
require(nftInfo[_nftId].staker == _msgSender(), "ERR__NOT_OWNER");
_sendRewardsForNft(_nftId, _to);
}
function getUpdatedAccTokenPerShare(address _baseToken) public view returns (uint256) {
uint256 accumulator = 0;
uint256 lastUpdatedTime = poolInfo[_baseToken].lastRewardTime;
uint256 counter = block.timestamp;
uint256 i = rewardRateLog[_baseToken].length - 1;
while (true) {
if (lastUpdatedTime >= counter) {
break;
}
unchecked {
accumulator +=
rewardRateLog[_baseToken][i].rewardsPerSecond *
(counter - max(lastUpdatedTime, rewardRateLog[_baseToken][i].timestamp));
}
counter = rewardRateLog[_baseToken][i].timestamp;
if (i == 0) {
break;
}
--i;
}
accumulator = (accumulator * ACC_TOKEN_PRECISION) / totalSharesStaked[_baseToken];
return accumulator + poolInfo[_baseToken].accTokenPerShare;
}
function pendingToken(uint256 _nftId) external view returns (uint256) {
NFTInfo storage nft = nftInfo[_nftId];
if (!nft.isStaked) {
return 0;
}
(address baseToken, , uint256 amount) = lpToken.tokenMetadata(_nftId);
amount /= liquidityProviders.BASE_DIVISOR();
PoolInfo memory pool = poolInfo[baseToken];
uint256 accToken1PerShare = pool.accTokenPerShare;
if (block.timestamp > pool.lastRewardTime && totalSharesStaked[baseToken] != 0) {
accToken1PerShare = getUpdatedAccTokenPerShare(baseToken);
}
return ((amount * accToken1PerShare) / ACC_TOKEN_PRECISION) - nft.rewardDebt + nft.unpaidRewards;
}
function updatePool(address _baseToken) public whenNotPaused returns (PoolInfo memory pool) {
pool = poolInfo[_baseToken];
if (block.timestamp > pool.lastRewardTime) {
if (totalSharesStaked[_baseToken] > 0) {
pool.accTokenPerShare = getUpdatedAccTokenPerShare(_baseToken);
}
pool.lastRewardTime = block.timestamp;
poolInfo[_baseToken] = pool;
emit LogUpdatePool(_baseToken, pool.lastRewardTime, totalSharesStaked[_baseToken], pool.accTokenPerShare);
}
}
function getNftIdsStaked(address _user) public view returns (uint256[] memory nftIds) {
nftIds = nftIdsStaked[_user];
}
function getRewardRatePerSecond(address _baseToken) public view returns (uint256) {
return rewardRateLog[_baseToken][rewardRateLog[_baseToken].length - 1].rewardsPerSecond;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override(IERC721ReceiverUpgradeable) returns (bytes4) {
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
receive() external payable {
emit LogNativeReceived(_msgSender(), msg.value);
}
function max(uint256 _a, uint256 _b) private pure returns (uint256) {
return _a >= _b ? _a : _b;
}
} | 3,011 | 276 | 3 | 1. [H-04] Deleting nft Info can cause users' `nft.unpaidRewards` to be permanently erased
When `withdraw()` is called, `_sendRewardsForNft(_nftId, _to)` will be called to send the rewards.
In `_sendRewardsForNft()`, when `address(this).balance` is insufficient at the moment, `nft.unpaidRewards = pending - balance` will be recorded and the user can get it back at the next time.
However, at L244, the whole nftInfo is being deleted, so that nft.unpaidRewards will also get erased.
2. [H-05] Users will lose a majority or even all of the rewards when the amount of total shares is too large, due to precision loss (Precision loss, Potential Incorrect Reward Calculation)
Function `getUpdatedAccTokenPerShare()`
3. [M-04] Owners have absolute control over protocol (Centralization risks, Unrestricted Access to Critical Functions)
Function `reclaimTokens()`
4. [M-06] DoS by gas limit (Gas Limit)
In `deposit()` function it is possible to push to `nftIdsStaked` of anyone, an attacker can deposit too many nfts to another user, and when the user will try to withdraw an nft at the end of the list, they will iterate on the list and revert because of gas limit.
5. [M-10] Call to non-existing contracts returns success (Unchecked external call)
Low level calls (call, delegate call and static call) return success if the called contract doesn’t exist (not deployed or destructed).
6. [M-14] LiquidityFarming.sol Unbounded for loops can potentially freeze users' funds in edge cases (Unbounded for loops)
In the current implementation of withdraw(), it calls _sendRewardsForNft() at L243 which calls updatePool() at L129 which calls getUpdatedAccTokenPerShare() at L319.
| 6 |
97_ LiquidityPool.sol | pragma solidity 0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./metatx/ERC2771ContextUpgradeable.sol";
import "../security/Pausable.sol";
import "./interfaces/IExecutorManager.sol";
import "./interfaces/ILiquidityProviders.sol";
import "../interfaces/IERC20Permit.sol";
import "./interfaces/ITokenManager.sol";
contract LiquidityPool is ReentrancyGuardUpgradeable, Pausable, OwnableUpgradeable, ERC2771ContextUpgradeable {
address private constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 private constant BASE_DIVISOR = 10000000000;
uint256 public baseGas;
IExecutorManager private executorManager;
ITokenManager public tokenManager;
ILiquidityProviders public liquidityProviders;
struct PermitRequest {
uint256 nonce;
uint256 expiry;
bool allowed;
uint8 v;
bytes32 r;
bytes32 s;
}
mapping(bytes32 => bool) public processedHash;
mapping(address => uint256) public gasFeeAccumulatedByToken;
mapping(address => mapping(address => uint256)) public gasFeeAccumulated;
mapping(address => uint256) public incentivePool;
event AssetSent(
address indexed asset,
uint256 indexed amount,
uint256 indexed transferredAmount,
address target,
bytes depositHash,
uint256 fromChainId
);
event FeeDetails(uint256 indexed lpFee, uint256 indexed transferFee, uint256 indexed gasFee);
event Received(address indexed from, uint256 indexed amount);
event Deposit(
address indexed from,
address indexed tokenAddress,
address indexed receiver,
uint256 toChainId,
uint256 amount,
uint256 reward,
string tag
);
event GasFeeWithdraw(address indexed tokenAddress, address indexed owner, uint256 indexed amount);
event TrustedForwarderChanged(address indexed forwarderAddress);
event LiquidityProvidersChanged(address indexed liquidityProvidersAddress);
event EthReceived(address, uint256);
modifier onlyExecutor() {
require(executorManager.getExecutorStatus(_msgSender()), "Only executor is allowed");
_;
}
modifier onlyLiquidityProviders() {
require(_msgSender() == address(liquidityProviders), "Only liquidityProviders is allowed");
_;
}
modifier tokenChecks(address tokenAddress) {
require(tokenAddress != address(0), "Token address cannot be 0");
require(tokenManager.getTokensInfo(tokenAddress).supportedToken, "Token not supported");
_;
}
function initialize(
address _executorManagerAddress,
address _pauser,
address _trustedForwarder,
address _tokenManager,
address _liquidityProviders
) public initializer {
require(_executorManagerAddress != address(0), "ExecutorManager cannot be 0x0");
require(_trustedForwarder != address(0), "TrustedForwarder cannot be 0x0");
require(_liquidityProviders != address(0), "LiquidityProviders cannot be 0x0");
__ERC2771Context_init(_trustedForwarder);
__ReentrancyGuard_init();
__Ownable_init();
__Pausable_init(_pauser);
executorManager = IExecutorManager(_executorManagerAddress);
tokenManager = ITokenManager(_tokenManager);
liquidityProviders = ILiquidityProviders(_liquidityProviders);
baseGas = 21000;
}
function setTrustedForwarder(address trustedForwarder) public onlyOwner {
require(trustedForwarder != address(0), "TrustedForwarder can't be 0");
_trustedForwarder = trustedForwarder;
emit TrustedForwarderChanged(trustedForwarder);
}
function setLiquidityProviders(address _liquidityProviders) public onlyOwner {
require(_liquidityProviders != address(0), "LiquidityProviders can't be 0");
liquidityProviders = ILiquidityProviders(_liquidityProviders);
emit LiquidityProvidersChanged(_liquidityProviders);
}
function setBaseGas(uint128 gas) external onlyOwner {
baseGas = gas;
}
function getExecutorManager() public view returns (address) {
return address(executorManager);
}
function setExecutorManager(address _executorManagerAddress) external onlyOwner {
require(_executorManagerAddress != address(0), "Executor Manager cannot be 0");
executorManager = IExecutorManager(_executorManagerAddress);
}
function getCurrentLiquidity(address tokenAddress) public view returns (uint256 currentLiquidity) {
uint256 liquidityPoolBalance = liquidityProviders.getCurrentLiquidity(tokenAddress);
currentLiquidity =
liquidityPoolBalance -
liquidityProviders.totalLPFees(tokenAddress) -
gasFeeAccumulatedByToken[tokenAddress] -
incentivePool[tokenAddress];
}
function depositErc20(
uint256 toChainId,
address tokenAddress,
address receiver,
uint256 amount,
string memory tag
) public tokenChecks(tokenAddress) whenNotPaused nonReentrant {
require(
tokenManager.getDepositConfig(toChainId, tokenAddress).min <= amount &&
tokenManager.getDepositConfig(toChainId, tokenAddress).max >= amount,
"Deposit amount not in Cap limit"
);
require(receiver != address(0), "Receiver address cannot be 0");
require(amount != 0, "Amount cannot be 0");
address sender = _msgSender();
uint256 rewardAmount = getRewardAmount(amount, tokenAddress);
if (rewardAmount != 0) {
incentivePool[tokenAddress] = incentivePool[tokenAddress] - rewardAmount;
}
liquidityProviders.increaseCurrentLiquidity(tokenAddress, amount);
SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(tokenAddress), sender, address(this), amount);
emit Deposit(sender, tokenAddress, receiver, toChainId, amount + rewardAmount, rewardAmount, tag);
}
function getRewardAmount(uint256 amount, address tokenAddress) public view returns (uint256 rewardAmount) {
uint256 currentLiquidity = getCurrentLiquidity(tokenAddress);
uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress);
if (currentLiquidity < providedLiquidity) {
uint256 liquidityDifference = providedLiquidity - currentLiquidity;
if (amount >= liquidityDifference) {
rewardAmount = incentivePool[tokenAddress];
} else {
rewardAmount = (amount * incentivePool[tokenAddress] * 10000000000) / liquidityDifference;
rewardAmount = rewardAmount / 10000000000;
}
}
}
function permitAndDepositErc20(
address tokenAddress,
address receiver,
uint256 amount,
uint256 toChainId,
PermitRequest calldata permitOptions,
string memory tag
) external {
IERC20Permit(tokenAddress).permit(
_msgSender(),
address(this),
permitOptions.nonce,
permitOptions.expiry,
permitOptions.allowed,
permitOptions.v,
permitOptions.r,
permitOptions.s
);
depositErc20(toChainId, tokenAddress, receiver, amount, tag);
}
function permitEIP2612AndDepositErc20(
address tokenAddress,
address receiver,
uint256 amount,
uint256 toChainId,
PermitRequest calldata permitOptions,
string memory tag
) external {
IERC20Permit(tokenAddress).permit(
_msgSender(),
address(this),
amount,
permitOptions.expiry,
permitOptions.v,
permitOptions.r,
permitOptions.s
);
depositErc20(toChainId, tokenAddress, receiver, amount, tag);
}
function depositNative(
address receiver,
uint256 toChainId,
string memory tag
) external payable whenNotPaused nonReentrant {
require(
tokenManager.getDepositConfig(toChainId, NATIVE).min <= msg.value &&
tokenManager.getDepositConfig(toChainId, NATIVE).max >= msg.value,
"Deposit amount not in Cap limit"
);
require(receiver != address(0), "Receiver address cannot be 0");
require(msg.value != 0, "Amount cannot be 0");
uint256 rewardAmount = getRewardAmount(msg.value, NATIVE);
if (rewardAmount != 0) {
incentivePool[NATIVE] = incentivePool[NATIVE] - rewardAmount;
}
liquidityProviders.increaseCurrentLiquidity(NATIVE, msg.value);
emit Deposit(_msgSender(), NATIVE, receiver, toChainId, msg.value + rewardAmount, rewardAmount, tag);
}
function sendFundsToUser(
address tokenAddress,
uint256 amount,
address payable receiver,
bytes memory depositHash,
uint256 tokenGasPrice,
uint256 fromChainId
) external nonReentrant onlyExecutor tokenChecks(tokenAddress) whenNotPaused {
uint256 initialGas = gasleft();
require(
tokenManager.getTransferConfig(tokenAddress).min <= amount &&
tokenManager.getTransferConfig(tokenAddress).max >= amount,
"Withdraw amnt not in Cap limits"
);
require(receiver != address(0), "Bad receiver address");
(bytes32 hashSendTransaction, bool status) = checkHashStatus(tokenAddress, amount, receiver, depositHash);
require(!status, "Already Processed");
processedHash[hashSendTransaction] = true;
uint256 amountToTransfer = getAmountToTransfer(initialGas, tokenAddress, amount, tokenGasPrice);
liquidityProviders.decreaseCurrentLiquidity(tokenAddress, amountToTransfer);
if (tokenAddress == NATIVE) {
require(address(this).balance >= amountToTransfer, "Not Enough Balance");
(bool success, ) = receiver.call{value: amountToTransfer}("");
require(success, "Native Transfer Failed");
} else {
require(IERC20Upgradeable(tokenAddress).balanceOf(address(this)) >= amountToTransfer, "Not Enough Balance");
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), receiver, amountToTransfer);
}
emit AssetSent(tokenAddress, amount, amountToTransfer, receiver, depositHash, fromChainId);
}
function getAmountToTransfer(
uint256 initialGas,
address tokenAddress,
uint256 amount,
uint256 tokenGasPrice
) internal returns (uint256 amountToTransfer) {
uint256 transferFeePerc = getTransferFee(tokenAddress, amount);
uint256 lpFee;
if (transferFeePerc > tokenManager.getTokensInfo(tokenAddress).equilibriumFee) {
lpFee = (amount * tokenManager.getTokensInfo(tokenAddress).equilibriumFee) / BASE_DIVISOR;
incentivePool[tokenAddress] =
(incentivePool[tokenAddress] +
(amount * (transferFeePerc - tokenManager.getTokensInfo(tokenAddress).equilibriumFee))) /
BASE_DIVISOR;
} else {
lpFee = (amount * transferFeePerc) / BASE_DIVISOR;
}
uint256 transferFeeAmount = (amount * transferFeePerc) / BASE_DIVISOR;
liquidityProviders.addLPFee(tokenAddress, lpFee);
uint256 totalGasUsed = initialGas - gasleft();
totalGasUsed = totalGasUsed + tokenManager.getTokensInfo(tokenAddress).transferOverhead;
totalGasUsed = totalGasUsed + baseGas;
uint256 gasFee = totalGasUsed * tokenGasPrice;
gasFeeAccumulatedByToken[tokenAddress] = gasFeeAccumulatedByToken[tokenAddress] + gasFee;
gasFeeAccumulated[tokenAddress][_msgSender()] = gasFeeAccumulated[tokenAddress][_msgSender()] + gasFee;
amountToTransfer = amount - (transferFeeAmount + gasFee);
emit FeeDetails(lpFee, transferFeeAmount, gasFee);
}
function getTransferFee(address tokenAddress, uint256 amount) public view returns (uint256 fee) {
uint256 currentLiquidity = getCurrentLiquidity(tokenAddress);
uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress);
uint256 resultingLiquidity = currentLiquidity - amount;
uint256 equilibriumFee = tokenManager.getTokensInfo(tokenAddress).equilibriumFee;
uint256 maxFee = tokenManager.getTokensInfo(tokenAddress).maxFee;
uint256 numerator = providedLiquidity * equilibriumFee * maxFee;
uint256 denominator = equilibriumFee * providedLiquidity + (maxFee - equilibriumFee) * resultingLiquidity;
if (denominator == 0) {
fee = 0;
} else {
fee = numerator / denominator;
}
}
function checkHashStatus(
address tokenAddress,
uint256 amount,
address payable receiver,
bytes memory depositHash
) public view returns (bytes32 hashSendTransaction, bool status) {
hashSendTransaction = keccak256(abi.encode(tokenAddress, amount, receiver, keccak256(depositHash)));
status = processedHash[hashSendTransaction];
}
function withdrawErc20GasFee(address tokenAddress) external onlyExecutor whenNotPaused nonReentrant {
require(tokenAddress != NATIVE, "Can't withdraw native token fee");
uint256 _gasFeeAccumulated = gasFeeAccumulated[tokenAddress][_msgSender()];
require(_gasFeeAccumulated != 0, "Gas Fee earned is 0");
gasFeeAccumulatedByToken[tokenAddress] = gasFeeAccumulatedByToken[tokenAddress] - _gasFeeAccumulated;
gasFeeAccumulated[tokenAddress][_msgSender()] = 0;
SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), _msgSender(), _gasFeeAccumulated);
emit GasFeeWithdraw(tokenAddress, _msgSender(), _gasFeeAccumulated);
}
function withdrawNativeGasFee() external onlyExecutor whenNotPaused nonReentrant {
uint256 _gasFeeAccumulated = gasFeeAccumulated[NATIVE][_msgSender()];
require(_gasFeeAccumulated != 0, "Gas Fee earned is 0");
gasFeeAccumulatedByToken[NATIVE] = gasFeeAccumulatedByToken[NATIVE] - _gasFeeAccumulated;
gasFeeAccumulated[NATIVE][_msgSender()] = 0;
(bool success, ) = payable(_msgSender()).call{value: _gasFeeAccumulated}("");
require(success, "Native Transfer Failed");
emit GasFeeWithdraw(address(this), _msgSender(), _gasFeeAccumulated);
}
function transfer(
address _tokenAddress,
address receiver,
uint256 _tokenAmount
) external whenNotPaused onlyLiquidityProviders nonReentrant {
require(receiver != address(0), "Invalid receiver");
if (_tokenAddress == NATIVE) {
require(address(this).balance >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE");
(bool success, ) = receiver.call{value: _tokenAmount}("");
require(success, "ERR__NATIVE_TRANSFER_FAILED");
} else {
IERC20Upgradeable baseToken = IERC20Upgradeable(_tokenAddress);
require(baseToken.balanceOf(address(this)) >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE");
SafeERC20Upgradeable.safeTransfer(baseToken, receiver, _tokenAmount);
}
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
receive() external payable {
emit EthReceived(_msgSender(), msg.value);
}
} | 3,554 | 347 | 1 | 1. [H-01] Can deposit native token for free and steal funds (Unchecked return values)
The `depositErc20` function allows setting tokenAddress = NATIVE and does not throw an error.
No matter the amount chosen, the `SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(tokenAddress), sender, address(this), amount);` call will not revert because it performs a low-level call to NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, which is an EOA, and the low-level calls to EOAs always succeed.
Because the safe* version is used, the EOA not returning any data does not revert either.
2. [H-03] Wrong formula when add fee incentivePool can lead to loss of funds. (Wrong computation)
The `getAmountToTransfer` function of LiquidityPool updates incentivePool[tokenAddress] by adding some fee to it but the formula is wrong and the value of incentivePool[tokenAddress] will be divided by BASE_DIVISOR (10000000000) each time. After just a few time, the value of incentivePool[tokenAddress] will become zero and that amount of tokenAddress token will be locked in contract.
3. [M-07] Sending tokens close to the maximum will fail and user will lose tokens
When a user calls the `deposit()` function the reward amount is calculated and an event is emited with amount+reward as the transfer amount. The function checks amount is smaller than the max amount.
4. [M-08] Incentive Pool can be drained without rebalancing the pool (Potential Gas Griefing in sendFundsToUse,Liquidity pool manipulation)
`depositErc20()` allows an attacker to specify the destination chain to be the same as the source chain and the receiver account to be the same as the caller account. This enables an attacker to drain the incentive pool without rebalancing the pool back to the equilibrium state. `sendFundsToUser()`
5. [M-13] Improper `tokenGasPrice` design can overcharge user for the gas cost by a huge margin
In function `getAmountToTransfer()`, When the Executor calls `sendFundsToUser()`, the tokenGasPrice will be used to calculate the gas fee for this transaction and it will be deducted from the transfer amount.
| 5 |
76_Sherlock.sol | pragma solidity 0.8.10;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import './interfaces/ISherlock.sol';
contract Sherlock is ISherlock, ERC721, Ownable, Pausable {
using SafeERC20 for IERC20;
uint256 public constant ARB_RESTAKE_WAIT_TIME = 2 weeks;
uint256 public constant ARB_RESTAKE_GROWTH_TIME = 1 weeks;
uint256 public constant ARB_RESTAKE_PERIOD = 12 weeks;
uint256 public constant ARB_RESTAKE_MAX_PERCENTAGE = (10**18 / 100) * 20;
IERC20 public immutable token;
IERC20 public immutable sher;
mapping(uint256 => bool) public override stakingPeriods;
mapping(uint256 => uint256) internal lockupEnd_;
mapping(uint256 => uint256) internal sherRewards_;
mapping(uint256 => uint256) internal stakeShares;
mapping(address => uint256) internal addressShares;
uint256 internal totalStakeShares;
IStrategyManager public override yieldStrategy;
ISherDistributionManager public override sherDistributionManager;
ISherlockProtocolManager public override sherlockProtocolManager;
ISherlockClaimManager public override sherlockClaimManager;
address public override nonStakersAddress;
uint256 internal nftCounter;
constructor(
IERC20 _token,
IERC20 _sher,
string memory _name,
string memory _symbol,
IStrategyManager _yieldStrategy,
ISherDistributionManager _sherDistributionManager,
address _nonStakersAddress,
ISherlockProtocolManager _sherlockProtocolManager,
ISherlockClaimManager _sherlockClaimManager,
uint256[] memory _initialstakingPeriods
) ERC721(_name, _symbol) {
if (address(_token) == address(0)) revert ZeroArgument();
if (address(_sher) == address(0)) revert ZeroArgument();
if (address(_yieldStrategy) == address(0)) revert ZeroArgument();
if (address(_sherDistributionManager) == address(0)) revert ZeroArgument();
if (_nonStakersAddress == address(0)) revert ZeroArgument();
if (address(_sherlockProtocolManager) == address(0)) revert ZeroArgument();
if (address(_sherlockClaimManager) == address(0)) revert ZeroArgument();
token = _token;
sher = _sher;
yieldStrategy = _yieldStrategy;
sherDistributionManager = _sherDistributionManager;
nonStakersAddress = _nonStakersAddress;
sherlockProtocolManager = _sherlockProtocolManager;
sherlockClaimManager = _sherlockClaimManager;
for (uint256 i; i < _initialstakingPeriods.length; i++) {
enableStakingPeriod(_initialstakingPeriods[i]);
}
emit YieldStrategyUpdated(IStrategyManager(address(0)), _yieldStrategy);
emit SherDistributionManagerUpdated(
ISherDistributionManager(address(0)),
_sherDistributionManager
);
emit NonStakerAddressUpdated(address(0), _nonStakersAddress);
emit ProtocolManagerUpdated(ISherlockProtocolManager(address(0)), _sherlockProtocolManager);
emit ClaimManagerUpdated(ISherlockClaimManager(address(0)), _sherlockClaimManager);
}
function lockupEnd(uint256 _tokenID) public view override returns (uint256) {
if (!_exists(_tokenID)) revert NonExistent();
return lockupEnd_[_tokenID];
}
function sherRewards(uint256 _tokenID) public view override returns (uint256) {
if (!_exists(_tokenID)) revert NonExistent();
return sherRewards_[_tokenID];
}
function tokenBalanceOf(uint256 _tokenID) public view override returns (uint256) {
if (!_exists(_tokenID)) revert NonExistent();
return (stakeShares[_tokenID] * totalTokenBalanceStakers()) / totalStakeShares;
}
function tokenBalanceOfAddress(address _staker) external view override returns (uint256) {
if (_staker == address(0)) revert ZeroArgument();
uint256 _totalStakeShares = totalStakeShares;
if (_totalStakeShares == 0) return 0;
return (addressShares[_staker] * totalTokenBalanceStakers()) / _totalStakeShares;
}
function totalTokenBalanceStakers() public view override returns (uint256) {
return
token.balanceOf(address(this)) +
yieldStrategy.balanceOf() +
sherlockProtocolManager.claimablePremiums();
}
function enableStakingPeriod(uint256 _period) public override onlyOwner {
if (_period == 0) revert ZeroArgument();
if (stakingPeriods[_period]) revert InvalidArgument();
stakingPeriods[_period] = true;
emit StakingPeriodEnabled(_period);
}
function disableStakingPeriod(uint256 _period) external override onlyOwner {
if (!stakingPeriods[_period]) revert InvalidArgument();
stakingPeriods[_period] = false;
emit StakingPeriodDisabled(_period);
}
function updateSherDistributionManager(ISherDistributionManager _sherDistributionManager)
external
override
onlyOwner
{
if (address(_sherDistributionManager) == address(0)) revert ZeroArgument();
if (sherDistributionManager == _sherDistributionManager) revert InvalidArgument();
emit SherDistributionManagerUpdated(sherDistributionManager, _sherDistributionManager);
sherDistributionManager = _sherDistributionManager;
}
function removeSherDistributionManager() external override onlyOwner {
if (address(sherDistributionManager) == address(0)) revert InvalidConditions();
emit SherDistributionManagerUpdated(
sherDistributionManager,
ISherDistributionManager(address(0))
);
delete sherDistributionManager;
}
function updateNonStakersAddress(address _nonStakers) external override onlyOwner {
if (address(_nonStakers) == address(0)) revert ZeroArgument();
if (nonStakersAddress == _nonStakers) revert InvalidArgument();
emit NonStakerAddressUpdated(nonStakersAddress, _nonStakers);
nonStakersAddress = _nonStakers;
}
function updateSherlockProtocolManager(ISherlockProtocolManager _protocolManager)
external
override
onlyOwner
{
if (address(_protocolManager) == address(0)) revert ZeroArgument();
if (sherlockProtocolManager == _protocolManager) revert InvalidArgument();
emit ProtocolManagerUpdated(sherlockProtocolManager, _protocolManager);
sherlockProtocolManager = _protocolManager;
}
function updateSherlockClaimManager(ISherlockClaimManager _claimManager)
external
override
onlyOwner
{
if (address(_claimManager) == address(0)) revert ZeroArgument();
if (sherlockClaimManager == _claimManager) revert InvalidArgument();
emit ClaimManagerUpdated(sherlockClaimManager, _claimManager);
sherlockClaimManager = _claimManager;
}
function updateYieldStrategy(IStrategyManager _yieldStrategy) external override onlyOwner {
if (address(_yieldStrategy) == address(0)) revert ZeroArgument();
if (yieldStrategy == _yieldStrategy) revert InvalidArgument();
try yieldStrategy.withdrawAll() {} catch (bytes memory reason) {
emit YieldStrategyUpdateWithdrawAllError(reason);
}
emit YieldStrategyUpdated(yieldStrategy, _yieldStrategy);
yieldStrategy = _yieldStrategy;
}
function yieldStrategyDeposit(uint256 _amount) external override onlyOwner {
if (_amount == 0) revert ZeroArgument();
sherlockProtocolManager.claimPremiumsForStakers();
token.safeTransfer(address(yieldStrategy), _amount);
yieldStrategy.deposit();
}
function yieldStrategyWithdraw(uint256 _amount) external override onlyOwner {
if (_amount == 0) revert ZeroArgument();
yieldStrategy.withdraw(_amount);
}
function yieldStrategyWithdrawAll() external override onlyOwner {
yieldStrategy.withdrawAll();
}
function pause() external onlyOwner {
_pause();
if (!Pausable(address(yieldStrategy)).paused()) yieldStrategy.pause();
if (
address(sherDistributionManager) != address(0) &&
!Pausable(address(sherDistributionManager)).paused()
) {
sherDistributionManager.pause();
}
if (!Pausable(address(sherlockProtocolManager)).paused()) sherlockProtocolManager.pause();
if (!Pausable(address(sherlockClaimManager)).paused()) sherlockClaimManager.pause();
}
function unpause() external onlyOwner {
_unpause();
if (Pausable(address(yieldStrategy)).paused()) yieldStrategy.unpause();
if (
address(sherDistributionManager) != address(0) &&
Pausable(address(sherDistributionManager)).paused()
) {
sherDistributionManager.unpause();
}
if (Pausable(address(sherlockProtocolManager)).paused()) sherlockProtocolManager.unpause();
if (Pausable(address(sherlockClaimManager)).paused()) sherlockClaimManager.unpause();
}
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenID
) internal override {
uint256 _stakeShares = stakeShares[_tokenID];
if (_from != address(0)) addressShares[_from] -= _stakeShares;
if (_to != address(0)) addressShares[_to] += _stakeShares;
}
function payoutClaim(address _receiver, uint256 _amount) external override whenNotPaused {
if (msg.sender != address(sherlockClaimManager)) revert Unauthorized();
if (_amount != 0) {
_transferTokensOut(_receiver, _amount);
}
emit ClaimPayout(_receiver, _amount);
}
function _stake(
uint256 _amount,
uint256 _period,
uint256 _id,
address _receiver
) internal returns (uint256 _sher) {
lockupEnd_[_id] = block.timestamp + _period;
if (address(sherDistributionManager) == address(0)) return 0;
if (_amount == 0) return 0;
uint256 before = sher.balanceOf(address(this));
_sher = sherDistributionManager.pullReward(_amount, _period, _id, _receiver);
uint256 actualAmount = sher.balanceOf(address(this)) - before;
if (actualAmount != _sher) revert InvalidSherAmount(_sher, actualAmount);
if (_sher != 0) sherRewards_[_id] = _sher;
}
function _verifyUnlockableByOwner(uint256 _id) internal view {
if (ownerOf(_id) != msg.sender) revert Unauthorized();
if (lockupEnd_[_id] > block.timestamp) revert InvalidConditions();
}
function _sendSherRewardsToOwner(uint256 _id, address _nftOwner) internal {
uint256 sherReward = sherRewards_[_id];
if (sherReward == 0) return;
sher.safeTransfer(_nftOwner, sherReward);
delete sherRewards_[_id];
}
function _transferTokensOut(address _receiver, uint256 _amount) internal {
sherlockProtocolManager.claimPremiumsForStakers();
uint256 mainBalance = token.balanceOf(address(this));
if (_amount > mainBalance) {
yieldStrategy.withdraw(_amount - mainBalance);
}
token.safeTransfer(_receiver, _amount);
}
function _redeemSharesCalc(uint256 _stakeShares) internal view returns (uint256) {
return (_stakeShares * totalTokenBalanceStakers()) / totalStakeShares;
}
function _redeemShares(
uint256 _id,
uint256 _stakeShares,
address _receiver
) internal returns (uint256 _amount) {
_amount = _redeemSharesCalc(_stakeShares);
if (_amount != 0) _transferTokensOut(_receiver, _amount);
stakeShares[_id] -= _stakeShares;
totalStakeShares -= _stakeShares;
}
function _restake(
uint256 _id,
uint256 _period,
address _nftOwner
) internal returns (uint256 _sher) {
_sendSherRewardsToOwner(_id, _nftOwner);
_sher = _stake(tokenBalanceOf(_id), _period, _id, _nftOwner);
emit Restaked(_id);
}
function initialStake(
uint256 _amount,
uint256 _period,
address _receiver
) external override whenNotPaused returns (uint256 _id, uint256 _sher) {
if (_amount == 0) revert ZeroArgument();
if (!stakingPeriods[_period]) revert InvalidArgument();
if (address(_receiver) == address(0)) revert ZeroArgument();
_id = ++nftCounter;
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 stakeShares_;
uint256 totalStakeShares_ = totalStakeShares;
if (totalStakeShares_ != 0)
stakeShares_ = (_amount * totalStakeShares_) / (totalTokenBalanceStakers() - _amount);
else stakeShares_ = _amount;
stakeShares[_id] = stakeShares_;
totalStakeShares += stakeShares_;
_sher = _stake(_amount, _period, _id, _receiver);
_safeMint(_receiver, _id);
}
function redeemNFT(uint256 _id) external override whenNotPaused returns (uint256 _amount) {
_verifyUnlockableByOwner(_id);
_burn(_id);
_amount = _redeemShares(_id, stakeShares[_id], msg.sender);
_sendSherRewardsToOwner(_id, msg.sender);
delete lockupEnd_[_id];
}
function ownerRestake(uint256 _id, uint256 _period)
external
override
whenNotPaused
returns (uint256 _sher)
{
_verifyUnlockableByOwner(_id);
if (!stakingPeriods[_period]) revert InvalidArgument();
_sher = _restake(_id, _period, msg.sender);
}
function _calcSharesForArbRestake(uint256 _id) internal view returns (uint256, bool) {
uint256 initialArbTime = lockupEnd_[_id] + ARB_RESTAKE_WAIT_TIME;
if (initialArbTime > block.timestamp) return (0, false);
uint256 maxRewardArbTime = initialArbTime + ARB_RESTAKE_GROWTH_TIME;
uint256 targetTime = block.timestamp < maxRewardArbTime ? block.timestamp : maxRewardArbTime;
uint256 maxRewardScaled = ARB_RESTAKE_MAX_PERCENTAGE * stakeShares[_id];
return (
((targetTime - initialArbTime) * maxRewardScaled) / (ARB_RESTAKE_GROWTH_TIME) / 10**18,
true
);
}
function viewRewardForArbRestake(uint256 _id) external view returns (uint256 profit, bool able) {
(profit, able) = _calcSharesForArbRestake(_id);
profit = _redeemSharesCalc(profit);
}
function arbRestake(uint256 _id)
external
override
whenNotPaused
returns (uint256 _sher, uint256 _arbReward)
{
address nftOwner = ownerOf(_id);
(uint256 arbRewardShares, bool able) = _calcSharesForArbRestake(_id);
if (!able) revert InvalidConditions();
_arbReward = _redeemShares(_id, arbRewardShares, msg.sender);
_sher = _restake(_id, ARB_RESTAKE_PERIOD, nftOwner);
emit ArbRestaked(_id, _arbReward);
}
} | 3,508 | 327 | 1 | 1. [M-02] tokenBalanceOfAddress of `nftOwner` becomes permanently incorrect after `arbRestake()` (Potential inconsistency in `arbRestake` function)
2. [M-03] `updateYieldStrategy()` will freeze some funds with the old Strategy if `yieldStrategy` fails to withdraw all the funds because of liquidity issues (No checks on strategy migration)
3. [M-04] Reenterancy in `_sendSherRewardsToOwner()` (Reentrancy) | 3 |
101_LenderPool.sol | pragma solidity 0.7.6;
pragma abicoder v2;
import '@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../interfaces/ISavingsAccount.sol';
import '../interfaces/IYield.sol';
import '../interfaces/ILenderPool.sol';
import '../interfaces/IVerification.sol';
import '../interfaces/IPooledCreditLine.sol';
import '../interfaces/IPooledCreditLineEnums.sol';
contract LenderPool is ERC1155Upgradeable, ReentrancyGuardUpgradeable, IPooledCreditLineEnums, ILenderPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
ISavingsAccount public immutable SAVINGS_ACCOUNT;
IPooledCreditLine public immutable POOLED_CREDIT_LINE;
IVerification public immutable VERIFICATION;
uint256 constant SCALING_FACTOR = 1e18;
struct LenderInfo {
uint256 borrowerInterestSharesWithdrawn;
uint256 yieldInterestWithdrawnShares;
}
struct LenderPoolConstants {
uint256 startTime;
address borrowAsset;
address collateralAsset;
uint256 borrowLimit;
uint256 minBorrowAmount;
address lenderVerifier;
address borrowAssetStrategy;
bool areTokensTransferable;
}
struct LenderPoolVariables {
mapping(address => LenderInfo) lenders;
uint256 sharesHeld;
uint256 borrowerInterestShares;
uint256 borrowerInterestSharesWithdrawn;
uint256 yieldInterestWithdrawnShares;
uint256 collateralHeld;
}
mapping(uint256 => LenderPoolConstants) public pooledCLConstants;
mapping(uint256 => LenderPoolVariables) public pooledCLVariables;
mapping(uint256 => uint256) public totalSupply;
modifier onlyPooledCreditLine() {
require(msg.sender == address(POOLED_CREDIT_LINE), 'LP:OPCL1');
_;
}
event Lend(uint256 indexed id, address indexed user, uint256 amount);
event WithdrawLiquidity(uint256 indexed id, address indexed user, uint256 shares);
event WithdrawLiquidityOnCancel(uint256 indexed id, address indexed user, uint256 amount);
event InterestWithdrawn(uint256 indexed id, address indexed user, uint256 shares);
event LiquidationWithdrawn(uint256 indexed id, address indexed user, uint256 collateralShare);
event Liquidated(uint256 indexed id, uint256 collateralLiquidated);
constructor(
address _pooledCreditLine,
address _savingsAccount,
address _verification
) {
require(_pooledCreditLine != address(0), 'LP:C1');
require(_savingsAccount != address(0), 'LP:C2');
require(_verification != address(0), 'LP:C3');
POOLED_CREDIT_LINE = IPooledCreditLine(_pooledCreditLine);
SAVINGS_ACCOUNT = ISavingsAccount(_savingsAccount);
VERIFICATION = IVerification(_verification);
}
function initialize() external initializer {
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
__ERC1155_init('URI');
}
function create(
uint256 _id,
address _lenderVerifier,
address _borrowAsset,
address _borrowAssetStrategy,
uint256 _borrowLimit,
uint256 _minBorrowAmount,
uint256 _collectionPeriod,
bool _areTokensTransferable
) external override nonReentrant onlyPooledCreditLine {
pooledCLConstants[_id].startTime = block.timestamp.add(_collectionPeriod);
pooledCLConstants[_id].borrowAsset = _borrowAsset;
pooledCLConstants[_id].borrowLimit = _borrowLimit;
pooledCLConstants[_id].minBorrowAmount = _minBorrowAmount;
pooledCLConstants[_id].lenderVerifier = _lenderVerifier;
pooledCLConstants[_id].borrowAssetStrategy = _borrowAssetStrategy;
pooledCLConstants[_id].areTokensTransferable = _areTokensTransferable;
uint256 allowance = SAVINGS_ACCOUNT.allowance(address(this), _borrowAsset, address(POOLED_CREDIT_LINE));
if (allowance != type(uint256).max) {
SAVINGS_ACCOUNT.approve(_borrowAsset, address(POOLED_CREDIT_LINE), type(uint256).max);
}
}
function lend(uint256 _id, uint256 _amount) external nonReentrant {
require(_amount != 0, 'LP:L1');
require(VERIFICATION.isUser(msg.sender, pooledCLConstants[_id].lenderVerifier), 'LP:L2');
require(block.timestamp < pooledCLConstants[_id].startTime, 'LP:L3');
uint256 _totalLent = totalSupply[_id];
uint256 _maxLent = pooledCLConstants[_id].borrowLimit;
require(_maxLent > _totalLent, 'LP:L4');
uint256 _amountToLend = _amount;
if (_totalLent.add(_amount) > _maxLent) {
_amountToLend = _maxLent.sub(_totalLent);
}
address _borrowAsset = pooledCLConstants[_id].borrowAsset;
IERC20(_borrowAsset).safeTransferFrom(msg.sender, address(this), _amountToLend);
_mint(msg.sender, _id, _amountToLend, '');
emit Lend(_id, msg.sender, _amountToLend);
}
function start(uint256 _id) external override nonReentrant {
uint256 _startTime = pooledCLConstants[_id].startTime;
require(_startTime != 0, 'LP:S1');
require(block.timestamp >= _startTime, 'LP:S2');
require(block.timestamp < POOLED_CREDIT_LINE.getEndsAt(_id), 'LP:S3');
uint256 _totalLent = totalSupply[_id];
require(_totalLent >= pooledCLConstants[_id].minBorrowAmount, 'LP:S4');
_accept(_id, _totalLent);
}
function _accept(uint256 _id, uint256 _amount) private {
address _borrowAsset = pooledCLConstants[_id].borrowAsset;
address _strategy = pooledCLConstants[_id].borrowAssetStrategy;
IERC20(_borrowAsset).safeApprove(_strategy, _amount);
pooledCLVariables[_id].sharesHeld = SAVINGS_ACCOUNT.deposit(_borrowAsset, _strategy, address(this), _amount);
POOLED_CREDIT_LINE.accept(_id, _amount, msg.sender);
pooledCLConstants[_id].borrowLimit = _amount;
delete pooledCLConstants[_id].startTime;
delete pooledCLConstants[_id].minBorrowAmount;
}
function borrowed(uint256 _id, uint256 _sharesBorrowed) external override nonReentrant onlyPooledCreditLine {
pooledCLVariables[_id].sharesHeld = pooledCLVariables[_id].sharesHeld.sub(_sharesBorrowed);
}
function repaid(
uint256 _id,
uint256 _sharesRepaid,
uint256 _interestShares
) external override nonReentrant onlyPooledCreditLine {
pooledCLVariables[_id].sharesHeld = pooledCLVariables[_id].sharesHeld.add(_sharesRepaid);
pooledCLVariables[_id].borrowerInterestShares = pooledCLVariables[_id].borrowerInterestShares.add(_interestShares);
}
function requestCancelled(uint256 _id) external override onlyPooledCreditLine {
delete pooledCLConstants[_id].startTime;
}
function terminate(uint256 _id, address _to) external override nonReentrant onlyPooledCreditLine {
address _strategy = pooledCLConstants[_id].borrowAssetStrategy;
address _borrowAsset = pooledCLConstants[_id].borrowAsset;
uint256 _borrowedTokens = pooledCLConstants[_id].borrowLimit;
uint256 _notBorrowed = _borrowedTokens.sub(POOLED_CREDIT_LINE.getPrincipal(_id));
uint256 _notBorrowedInShares = IYield(_strategy).getSharesForTokens(_notBorrowed, _borrowAsset);
uint256 _sharesHeld = pooledCLVariables[_id].sharesHeld;
if (_sharesHeld != 0) {
uint256 _totalInterestInShares = _sharesHeld.sub(_notBorrowedInShares);
uint256 _actualNotBorrowedInShares = _notBorrowedInShares.mul(totalSupply[_id]).div(_borrowedTokens);
uint256 _totalBorrowAsset = _actualNotBorrowedInShares.add(_totalInterestInShares);
if (_totalBorrowAsset != 0) {
SAVINGS_ACCOUNT.withdrawShares(_borrowAsset, _strategy, _to, _totalBorrowAsset, false);
}
}
uint256 _collateralHeld = pooledCLVariables[_id].collateralHeld;
if (_collateralHeld != 0) {
IERC20(pooledCLConstants[_id].collateralAsset).safeTransfer(_to, _collateralHeld);
}
delete pooledCLConstants[_id];
delete pooledCLVariables[_id];
}
function withdrawInterest(uint256 _id) external nonReentrant {
uint256 _interestSharesWithdrawn = _withdrawInterest(_id, msg.sender);
require(_interestSharesWithdrawn != 0, 'LP:WI1');
}
function _withdrawInterest(uint256 _id, address _lender) private returns (uint256 _interestSharesWithdrawn) {
address _strategy = pooledCLConstants[_id].borrowAssetStrategy;
address _borrowAsset = pooledCLConstants[_id].borrowAsset;
require(_strategy != address(0), 'LP:IWI1');
uint256 _interestSharesToWithdraw = _updateInterestSharesToWithdraw(_id, _lender, _strategy, _borrowAsset);
if (_interestSharesToWithdraw != 0) {
pooledCLVariables[_id].sharesHeld = pooledCLVariables[_id].sharesHeld.sub(_interestSharesToWithdraw);
SAVINGS_ACCOUNT.withdrawShares(_borrowAsset, _strategy, _lender, _interestSharesToWithdraw, false);
emit InterestWithdrawn(_id, _lender, _interestSharesToWithdraw);
}
return _interestSharesToWithdraw;
}
function _updateInterestSharesToWithdraw(
uint256 _id,
address _lender,
address _strategy,
address _borrowAsset
) private returns (uint256) {
uint256 _lenderBalance = balanceOf(_lender, _id);
if (_lenderBalance == 0) {
return 0;
}
uint256 _borrowLimit = pooledCLConstants[_id].borrowLimit;
(uint256 _borrowerInterestSharesForLender, uint256 _yieldInterestSharesForLender) = _calculateLenderInterest(
_id,
_lender,
_strategy,
_borrowAsset,
_lenderBalance,
_borrowLimit
);
if (_borrowerInterestSharesForLender != 0) {
pooledCLVariables[_id].lenders[_lender].borrowerInterestSharesWithdrawn = pooledCLVariables[_id]
.lenders[_lender]
.borrowerInterestSharesWithdrawn
.add(_borrowerInterestSharesForLender);
pooledCLVariables[_id].borrowerInterestSharesWithdrawn = pooledCLVariables[_id].borrowerInterestSharesWithdrawn.add(
_borrowerInterestSharesForLender
);
}
if (_yieldInterestSharesForLender != 0) {
pooledCLVariables[_id].lenders[_lender].yieldInterestWithdrawnShares = pooledCLVariables[_id]
.lenders[_lender]
.yieldInterestWithdrawnShares
.add(_yieldInterestSharesForLender);
pooledCLVariables[_id].yieldInterestWithdrawnShares = pooledCLVariables[_id].yieldInterestWithdrawnShares.add(
_yieldInterestSharesForLender
);
}
return _yieldInterestSharesForLender.add(_borrowerInterestSharesForLender);
}
function getLenderInterestWithdrawable(uint256 _id, address _lender) external returns (uint256) {
address _strategy = pooledCLConstants[_id].borrowAssetStrategy;
address _borrowAsset = pooledCLConstants[_id].borrowAsset;
(uint256 _borrowerInterestShares, uint256 _yieldInterestShares) = _calculateLenderInterest(
_id,
_lender,
_strategy,
_borrowAsset,
balanceOf(_lender, _id),
pooledCLConstants[_id].borrowLimit
);
return IYield(_strategy).getTokensForShares(_borrowerInterestShares.add(_yieldInterestShares), _borrowAsset);
}
function _calculateLenderInterest(
uint256 _id,
address _lender,
address _strategy,
address _borrowAsset,
uint256 _lenderBalance,
uint256 _borrowLimit
) private returns (uint256 _borrowerInterestSharesForLender, uint256 _yieldInterestSharesForLender) {
uint256 _totalInterestWithdrawableInShares;
{
uint256 _sharesHeld = pooledCLVariables[_id].sharesHeld;
if (_sharesHeld == 0) {
return (0, 0);
}
uint256 _notBorrowed = _borrowLimit.sub(POOLED_CREDIT_LINE.getPrincipal(_id));
uint256 _notBorrowedInShares = IYield(_strategy).getSharesForTokens(_notBorrowed, _borrowAsset);
_totalInterestWithdrawableInShares = _sharesHeld.sub(_notBorrowedInShares);
}
uint256 _borrowerInterestShares = pooledCLVariables[_id].borrowerInterestShares;
_borrowerInterestSharesForLender = (_borrowerInterestShares.mul(_lenderBalance).div(_borrowLimit)).sub(
pooledCLVariables[_id].lenders[_lender].borrowerInterestSharesWithdrawn
);
{
uint256 _borrowerInterestWithdrawableInShares = _borrowerInterestShares.sub(
pooledCLVariables[_id].borrowerInterestSharesWithdrawn
);
_yieldInterestSharesForLender = 0;
if (_totalInterestWithdrawableInShares > _borrowerInterestWithdrawableInShares) {
uint256 _totalYieldInterestShares = _totalInterestWithdrawableInShares.sub(_borrowerInterestWithdrawableInShares).add(
pooledCLVariables[_id].yieldInterestWithdrawnShares
);
_yieldInterestSharesForLender = (_totalYieldInterestShares.mul(_lenderBalance).div(_borrowLimit)).sub(
pooledCLVariables[_id].lenders[_lender].yieldInterestWithdrawnShares
);
}
}
}
function withdrawLiquidity(uint256 _id) external nonReentrant {
_withdrawLiquidity(_id, false);
}
function _withdrawLiquidity(uint256 _id, bool _isLiquidationWithdrawn) private {
uint256 _liquidityProvided = balanceOf(msg.sender, _id);
require(_liquidityProvided != 0, 'LP:IWL1');
PooledCreditLineStatus _status = POOLED_CREDIT_LINE.getStatusAndUpdate(_id);
address _borrowAsset = pooledCLConstants[_id].borrowAsset;
if (_status == PooledCreditLineStatus.REQUESTED) {
if (block.timestamp >= pooledCLConstants[_id].startTime && totalSupply[_id] < pooledCLConstants[_id].minBorrowAmount) {
POOLED_CREDIT_LINE.cancelRequestOnLowCollection(_id);
} else if (block.timestamp >= POOLED_CREDIT_LINE.getEndsAt(_id)) {
POOLED_CREDIT_LINE.cancelRequestOnRequestedStateAtEnd(_id);
} else {
revert('LP:IWL3');
}
_status = PooledCreditLineStatus.CANCELLED;
delete pooledCLConstants[_id].startTime;
}
if (_status == PooledCreditLineStatus.CANCELLED) {
IERC20(_borrowAsset).safeTransfer(msg.sender, _liquidityProvided);
emit WithdrawLiquidityOnCancel(_id, msg.sender, _liquidityProvided);
} else if (_status == PooledCreditLineStatus.CLOSED || _status == PooledCreditLineStatus.LIQUIDATED) {
if (_status == PooledCreditLineStatus.LIQUIDATED) {
require(_isLiquidationWithdrawn, 'LP:IWL2');
}
address _strategy = pooledCLConstants[_id].borrowAssetStrategy;
uint256 _principalWithdrawable = _calculatePrincipalWithdrawable(_id, msg.sender);
uint256 _interestSharesWithdrawable = _updateInterestSharesToWithdraw(_id, msg.sender, _strategy, _borrowAsset);
uint256 _interestWithdrawable;
if (_interestSharesWithdrawable != 0) {
_interestWithdrawable = IYield(_strategy).getTokensForShares(_interestSharesWithdrawable, _borrowAsset);
pooledCLVariables[_id].sharesHeld = pooledCLVariables[_id].sharesHeld.sub(_interestSharesWithdrawable);
}
uint256 _amountToWithdraw = _principalWithdrawable.add(_interestWithdrawable);
uint256 _sharesToWithdraw = IYield(_strategy).getSharesForTokens(_amountToWithdraw, _borrowAsset);
if (_sharesToWithdraw != 0) {
SAVINGS_ACCOUNT.withdrawShares(_borrowAsset, _strategy, msg.sender, _sharesToWithdraw, false);
}
emit WithdrawLiquidity(_id, msg.sender, _sharesToWithdraw);
} else {
revert('LP:IWL3');
}
_burn(msg.sender, _id, _liquidityProvided);
}
function calculatePrincipalWithdrawable(uint256 _id, address _lender) external returns (uint256) {
PooledCreditLineStatus _status = POOLED_CREDIT_LINE.getStatusAndUpdate(_id);
if (_status == PooledCreditLineStatus.CLOSED || _status == PooledCreditLineStatus.LIQUIDATED) {
return _calculatePrincipalWithdrawable(_id, _lender);
} else if (
_status == PooledCreditLineStatus.CANCELLED ||
(_status == PooledCreditLineStatus.REQUESTED &&
((block.timestamp >= pooledCLConstants[_id].startTime && totalSupply[_id] < pooledCLConstants[_id].minBorrowAmount) ||
block.timestamp >= POOLED_CREDIT_LINE.getEndsAt(_id)))
) {
return balanceOf(_lender, _id);
} else {
return 0;
}
}
function _calculatePrincipalWithdrawable(uint256 _id, address _lender) private view returns (uint256) {
uint256 _borrowedTokens = pooledCLConstants[_id].borrowLimit;
uint256 _totalLiquidityWithdrawable = _borrowedTokens.sub(POOLED_CREDIT_LINE.getPrincipal(_id));
uint256 _principalWithdrawable = _totalLiquidityWithdrawable.mul(balanceOf(_lender, _id)).div(_borrowedTokens);
return _principalWithdrawable;
}
function liquidate(uint256 _id, bool _withdraw) external nonReentrant {
uint256 _lendingShare = balanceOf(msg.sender, _id);
require(_lendingShare != 0, 'LP:LIQ1');
(address _collateralAsset, uint256 _collateralLiquidated) = POOLED_CREDIT_LINE.liquidate(_id);
pooledCLConstants[_id].collateralAsset = _collateralAsset;
pooledCLVariables[_id].collateralHeld = _collateralLiquidated;
emit Liquidated(_id, _collateralLiquidated);
if (_withdraw) {
_withdrawTokensAfterLiquidation(_id, _lendingShare);
}
}
function withdrawTokensAfterLiquidation(uint256 _id) external nonReentrant {
uint256 _lendingShare = balanceOf(msg.sender, _id);
require(_lendingShare != 0, 'LP:WLC1');
_withdrawTokensAfterLiquidation(_id, _lendingShare);
}
function _withdrawTokensAfterLiquidation(uint256 _id, uint256 _balance) private {
address _collateralAsset = pooledCLConstants[_id].collateralAsset;
require(_collateralAsset != address(0), 'LP:IWLC1');
uint256 _collateralLiquidated = pooledCLVariables[_id].collateralHeld;
uint256 _currentSupply = totalSupply[_id];
uint256 _lenderCollateralShare = _balance.mul(_collateralLiquidated).div(_currentSupply);
if (_lenderCollateralShare != 0) {
pooledCLVariables[_id].collateralHeld = pooledCLVariables[_id].collateralHeld.sub(_lenderCollateralShare);
IERC20(_collateralAsset).safeTransfer(msg.sender, _lenderCollateralShare);
emit LiquidationWithdrawn(_id, msg.sender, _lenderCollateralShare);
}
_withdrawLiquidity(_id, true);
}
function _beforeTokenTransfer(
address,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory
) internal override {
require(from != to, 'LP:IT1');
for (uint256 i; i < ids.length; ++i) {
uint256 id = ids[i];
if (to != address(0)) {
require(to != POOLED_CREDIT_LINE.getBorrowerAddress(id), 'LP:IT2');
require(VERIFICATION.isUser(to, pooledCLConstants[id].lenderVerifier), 'LP:IT3');
}
uint256 amount = amounts[i];
if (from == address(0)) {
totalSupply[id] = totalSupply[id].add(amount);
} else if (to == address(0)) {
uint256 supply = totalSupply[id];
require(supply >= amount, 'LP:IT4');
totalSupply[id] = supply - amount;
} else {
require(pooledCLConstants[id].areTokensTransferable, 'LP:IT5');
}
if (from != address(0)) {
_rebalanceInterestWithdrawn(id, amount, from, to);
}
}
}
function _rebalanceInterestWithdrawn(
uint256 id,
uint256 amount,
address from,
address to
) private {
if (from != address(0) && to != address(0)) {
_withdrawInterest(id, from);
_withdrawInterest(id, to);
}
uint256 fromBalance = balanceOf(from, id);
require(fromBalance != 0, 'LP:IRIW1');
uint256 yieldInterestOnTransferAmount = pooledCLVariables[id].lenders[from].yieldInterestWithdrawnShares.mul(amount).div(
fromBalance
);
uint256 borrowerInterestOnTransferAmount = pooledCLVariables[id].lenders[from].borrowerInterestSharesWithdrawn.mul(amount).div(
fromBalance
);
if (borrowerInterestOnTransferAmount != 0) {
pooledCLVariables[id].lenders[from].borrowerInterestSharesWithdrawn = pooledCLVariables[id]
.lenders[from]
.borrowerInterestSharesWithdrawn
.sub(borrowerInterestOnTransferAmount);
}
if (yieldInterestOnTransferAmount != 0) {
pooledCLVariables[id].lenders[from].yieldInterestWithdrawnShares = pooledCLVariables[id]
.lenders[from]
.yieldInterestWithdrawnShares
.sub(yieldInterestOnTransferAmount);
}
if (to != address(0)) {
if (borrowerInterestOnTransferAmount != 0) {
pooledCLVariables[id].lenders[to].borrowerInterestSharesWithdrawn = pooledCLVariables[id]
.lenders[to]
.borrowerInterestSharesWithdrawn
.add(borrowerInterestOnTransferAmount);
}
if (yieldInterestOnTransferAmount != 0) {
pooledCLVariables[id].lenders[to].yieldInterestWithdrawnShares = pooledCLVariables[id]
.lenders[to]
.yieldInterestWithdrawnShares
.add(yieldInterestOnTransferAmount);
}
}
}
function getLenderInfo(uint256 _id, address _lender) external view returns (LenderInfo memory) {
return pooledCLVariables[_id].lenders[_lender];
}
} | 5,347 | 442 | 2 | 1. [H-01] LenderPool: Principal withdrawable is incorrectly calculated if start() is invoked with non-zero start fee
`_withdrawLiquidity` function
The `_principalWithdrawable` calculated will be more than expected if _start() is invoked with a non-zero start fee, because the borrow limit is reduced by the fee, resulting in totalSupply[id] not being 1:1 with the borrow limit.
2. [H-02] PooledCreditLine: termination likely fails because `_principalWithdrawable` is treated as shares
In `_withdrawLiquidity()`
3. [M-02] Lack of access control allow anyone to `withdrawInterest()` for any lender () (Lack of access control)
4. [M-03] Potentially depositing at unfavorable rate since anyone can deposit the entire lenderPool to a known strategy at a pre-fixed time (Timestamp Manipulation) | 4 |
51_AirdropDistribution.sol | pragma solidity ^0.8.4;
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import "./interfaces/IVesting.sol";
contract AirdropDistribution is Pausable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address[210] airdropArray = [
0x28d6037EDEAf8ec2c91c9b2cF9A1643111d8F198,
0xcfc50541c3dEaf725ce738EF87Ace2Ad778Ba0C5,
0xF9e11762d522ea29Dd78178c9BAf83b7B093aacc,
0xED60d8590019e5E145ea81455c01F3e817Fe54EB,
0x052564eB0fd8b340803dF55dEf89c25C432f43f4,
0x21F3B2C8646B4fFA809406BB31dE325a3E5E9b9F,
0xd9A93390c487b954EB1Ad4c8a4Acc73840409869,
0xe15DD1510E39E9980C0dC47e404eb7298872bc64,
0x3BA21b6477F48273f41d241AA3722FFb9E07E247,
0x2326D4fb2737666DDA96bd6314e3D4418246cFE8,
0xa0f75491720835b36edC92D06DDc468D201e9b73,
0xAc6559dF1F410Feba9a6cbf395272189461D8463,
0xAE60C874eE07f44fB7BBbD1a5087cDB66E90BEd8,
0x600b8A34ec1CfD8B8aF78cFC49708419A16ea2e8,
0x89689dB564BF4b67BD7116B3f71e68A379FAad98,
0xCaEDCaaFE4C596e89704c5e6B499B8D3474F750f,
0xbC90B3Ce40fc3Ed921D910f3e046C65954fFF7cB,
0x303985ba2209b5c0c745885Fa6fdd2eC1FEB81A5,
0x3991ADBDf461D6817734555efDC8ef056fEfBF21,
0xADEEb9d09B8Bcee10943198FB6F6a4229bAB3675,
0xb9a954BF995bDEAcBDfE4B1F5f85cD6122c6E341,
0x86aF94E5E8d3D583575bBafDD2DcB6b898A555e4,
0x270d2924cA13F54632601647FB225DB8eb61fB49,
0x02e05dbBF4df5d17cb3A0140F9643fE68cc4Ae39,
0xd8D3d8ab22E30c5402AB2A2E216a4A53F4e09e9E,
0x28a55C4b4f9615FDE3CDAdDf6cc01FcF2E38A6b0,
0x78Bc49be7bae5e0eeC08780c86F0e8278B8B035b,
0xf0E12c7218cB38DF7A3A231Bb91EE82F732625b6,
0x99eb33756a2eAa32f5964A747722c4b59e6aF351,
0xB0ff496dF3860504ebdFF61590A13c1D810C97cc,
0x40d2Ce4C14f04bD91c59c6A1CD6e28F2A0fc81F8,
0xF07F2B6C340d8D303615710451C11e93fe56774D,
0x6979B914f3A1d8C0fec2C1FD602f0e674cdf9862,
0x90be4e1Da4BB2F464576749abAc99774148bC9a2,
0x681148725731F213b0187A3CBeF215C291D85a3E,
0x1678b549Be696b1DfCe9F0639D996a82409E1Ea1,
0x4f58985B75EeC8f14C536878A19EAdF4a1960D6c,
0x55b9c56668365d11f5aF18E8b7232bC6e4d20658,
0xA423fE4CFb811E9CF6a61a02e80E372c0970d4b0,
0x7432b5212F19af018b33b73a55d1996960E59c51,
0x0Af14239FAA4f19034f3334502ED592B0083e108,
0x9fA933f60BCc5E63F75F210929839f91F55b919C,
0xB680f628C56C8Fa368Dacbb0C27beEf8C98355b9,
0x4EC7CdF61405758f5cED5E454c0B4b0F4F043DF0,
0xFCa7C5CF95821f3D45b9949De6E2846D66aF819F,
0xA7758B30e93d2ED6CEA7c85e5B12a1d46F0f091f,
0x84740F97Aea62C5dC36756DFD9F749412534220E,
0xcE968c0fC101C4FB8e08EB5dB73E7E169A2A3562,
0xC151AE135F50AaBE78e0b9D13A90FBb2d648AAbB,
0x975f5ffB9C3B624351634889944355D47Ab8a367,
0x9B5ea8C719e29A5bd0959FaF79C9E5c8206d0499,
0xF1fb5dEa21337FEB46963C29d04A95F6CA8B71e6,
0x71F12a5b0E60d2Ff8A87FD34E7dcff3c10c914b0,
0x918A97AD195DD111C54Ea82E2F8B8D22E9f48726,
0x25431341A5800759268a6aC1d3CD91C029D7d9CA,
0x52Ad87832400485DE7E7dC965D8Ad890f4e82699,
0xF38140985B5a5746F160F133049E83F79cc0B819,
0xbE93d14C5dEFb8F41aF8FB092F58e3C71C712b85,
0xa0a6Dc36041fb386378458006FEcbDdD02555DdD,
0x5F82C97e9b1755237692a946aE814998Bc0e2124,
0xdD709cAE362972cb3B92DCeaD77127f7b8D58202,
0x8b7B509c01838a0D197a8154C5BF00A3F56fF615,
0x640E0118b2C5a3C0Ea29B94A62d9108ce2c6ced7,
0x1B51cCe51E2531C478daA9b68eb80D47247dCbec,
0xcCa71809E8870AFEB72c4720d0fe50d5C3230e05,
0x2dE640a18fE3480aa802aca91f70177aDA103391,
0x14Ce500a86F1e3aCE039571e657783E069643617,
0x6019D32e59Ef480F2215eE9773AE507645B47bdc,
0xB67D92DC830F1a24E4BFfd1a6794fCf8f497c7de,
0x6f9BB7e454f5B3eb2310343f0E99269dC2BB8A1d,
0xE95d3DAbA7495d42DCC20810f33eeb5207512a9f,
0x39c09fdc4E5C5AB72F6319dDbc2CAe40E67b2A60,
0xFadAFCE89EA2221fa33005640Acf2C923312F2b9,
0x7122FC3588fB9E9B93b7c42Ba02FC85ef15c442b,
0x25AfD857C7831C91951Cd94ba63AF237d28604D0,
0x6fcF92925e0281D957B0076d3751caD76916C96B,
0xd026bFdB74fe1bAF1E1F1058f0d008cD1EEEd8B5,
0xbdC38612397355e10A2d6DD697a92f35BF1C9935,
0x339Dab47bdD20b4c05950c4306821896CFB1Ff1A,
0x1EBb814C9EF016E6012bE299ED834f1dDcEd1529,
0xF625DCa051B5AE56f684C072c09969C9Aa91478a,
0x5eBdC5C097F9378c3113DC2f9E8B51246E641896,
0xD45FBD8F2B0A84743D2606DE8094f86Fac5B6ed3,
0x3e89F0eCACDC9b1f8BB892367610cAd0cE421C92,
0xC77C0EDc7067a76972481484B87c1226E410547C,
0x0F763341b448bb0f02370F4037FE4A2c84c9283f,
0x0035Fc5208eF989c28d47e552E92b0C507D2B318,
0xB8C30017B375bf675c2836c4c6B6ed5BE214739d,
0x286ed1111c29592cC6240194b8d66E64B1c05e50,
0x4Cd52B37fdDD19CcD24B0d0e9a048785C7aaFCEf,
0x0D779D67a428457CAbEC145A0f94703D14cd496B,
0x0000A441fBB1fBAADF246539BF253A42ABD31494,
0xECB949c68C825650fD9D0Aebe0cd3796FD126e66,
0x8C4d5F3eaC04072245654E0BA480f1a5e1d91Dd5,
0xFca32B89d0981e69C8dadCDcc0668b0E01c810CF,
0x22fa8Cc33a42320385Cbd3690eD60a021891Cb32,
0x23Be060093Db74f38B1a3daF57AfDc1a23dB0077,
0xfc80d0867822b8eD010bafcC195c21617C01f943,
0x526C7665C5dd9cD7102C6d42D407a0d9DC1e431d,
0x6c5384bBaE7aF65Ed1b6784213A81DaE18e528b2,
0xAE667Ed58c0d9198fc0b9261156d48296C1bB3da,
0xe1DE283EAb72A68f7Ff972fcA13f8953c6e15e51,
0xdae88e81e10d848BA6b0Ad64B19783e807064696,
0x0a8A06071c878DF9Ec2B5f9663A4b08B0F8c08f4,
0x3E95fEF1176acF5e5d2EF67D9C856E4ECAc73E1F,
0x9C3c75c9D269aa8282BDE7BE3352D81CC91C2b6A,
0xD72B03B7F2E0b8D92b868E73e12b1f888BEFBeDA,
0xC23ef3AdF050f4Ca50b30998D37Eb6464e387577,
0xD56705548111F08CCB3e1A73806c53Dc706F2e75,
0x32802F989B4348A51DD0E61D23B78BE1a0543469,
0xc7ca02DC88A2750031DC04515438C3a505bcC994,
0x1eccd61c9fa53a8D2e823A26cD72A7efD7D0E92e,
0xa53A6fE2d8Ad977aD926C485343Ba39f32D3A3F6,
0x6b30E020E9517c519C408f51C2593E12D55B55fA,
0x57d1E246D2E32F6F9D10EC55Fc41E8B2E2988308,
0xEd557994671DddA053a582e73F2e8aa32bDE7D68,
0xceA077172675bf31e879Bba71fb46C3188591070,
0x3fC925E779F148f2d843cfD63296E5E12C36d632,
0xC369B30c8eC960260631E20081A32e4c61E5Ea9d,
0x8d4BfE71379a197ae0c3ea8B41b75f30294d6afb,
0x455d7Eb74860d0937423b9184f9e8461aa354Ebb,
0x14559df3FBe66Cab6F893D8dD53F7BFE68DE9C65,
0x238F24101876377E9178d125D0747DE7fad9C3b2,
0x4BB633f0e7E0F3FbC95a7f7fd223652882977573,
0x9BdFAeB9CB28DC05b09B37c0F14ECBc9A876CEe0,
0x7904aDB48351aF7b835Cb061316795d5226b7f1a,
0xF96dA4775776ea43c42795b116C7a6eCcd6e71b5,
0x418Efa84214F9810AF9119909D5bEe2c56ebd5Eb,
0x2c9dB5597a4a9d2ba6780CD9722e25A9140552EE,
0xe1163DCFb598F74da146a83CC878731d553abBfe,
0x0991D02f28a5283338e9591CBf7dE2eb25da46Cd,
0x7374bB48A5FDc16C9b216F3fCc60b105c73D1806,
0xe4f9E812Fe379128f17258A2b3Db7CF28613f190,
0x2CA3a2b525E75b2F20f59dEcCaE3ffa4bdf3EAa2,
0x8522885d735F75b3FAEEa5CD39ab3d1291dA2C77,
0xA4bd4E4D2e8c72720839823f6c20f411f7DDb1f1,
0x1729f93e3c3C74B503B8130516984CED70bF47D9,
0x94Da725DBA289B96f115ec955aDcAAA806d2085d,
0x38857Ed3a8fC5951289E58e20fB56A00e88f0BBD,
0x767D222a509D107522e50161CA17FfCF0e5AA3dE,
0xA4f2b2557D78E31D48E1ffa8AF8b25Db8524Ea3c,
0xDEC1BcdF22A6e77F10e3bF7df8a5F6A6a38E6376,
0xC1a0fC4a40253B04a1aE2F40655d73b16CAf268c,
0x285E4f019a531e20f673B634D31922d408970798,
0x2848b9f2D4FaEBaA4838c41071684c70688B455d,
0xa734288DA3aCE7F9a5e5CAa6Df929126f2e67d52,
0xD18001F022154654149ed45888C9c29Def6d3CE6,
0x7ea1a45f0657D2Dbd77839a916AB83112bdB5590,
0x058B10CbE1872ad139b00326686EE8CCef274C58,
0xc78CE4E51611ed720eC96bf584bf1b1658FD2379,
0xFbEd5277E524113Df313F9f6B29fDE8677F4E936,
0xA652565dB815Ad3B138fD98830D14Cfd1826693A,
0x43E553fC1D064C125764E9D534a4F7D89B9bb1BE,
0x1712fdDC84EFa346D51261f0fa5a809fF457aBDc,
0xD0a5266b2515c3b575e30cBC0cfC775FA4fC6660,
0x507E964A2fabE1921278b640b0813a5626844145,
0x51A7EaD10340AF963C3124b026b86dd2807c2b1C,
0x215D67998DaCd9DA4118E4a4899bec60b79987A0,
0x8fC548B6B071bf0f2Fe64aD1Aa6032A6d2037366,
0x102902245322aAd61D55cfAD8213472A5702a593,
0x4B4De68ef03aE45c0d1026801Da71258DDC6BCF6,
0x32a59b87352e980dD6aB1bAF462696D28e63525D,
0xE582794320FA7424A1f9db360A46446244065Cb5,
0xD71C552a4954673a30893BF1Db0A77f1aFA1accD,
0xEE4a267E98260aCf829Ca9dC6c9f3d5d82183Bce,
0x54683a50f0D2B3F3d1b32780524AE01AA1A583c2,
0xdc34F2a567dFE0E7512108b24EcEa2d92754751C,
0xD09c6b71b1a7841e7dFb244D90d2a146201BF78B,
0xbB48c430C3cA821755547E514A8Fe9CC82BDD975,
0x7F326eA697EF0dd2BbD628B62F569017c1D43FCB,
0x7f048Fe4176AB39E225907F777F658a6eFDD42ce,
0x66EA1467282FFf8df570a1f732F0C6Ab8749154E,
0xc1cAd6df277106222Dd45cF5B0300fBd4d1193D5,
0x963D071201275fD5FA3dC9bB34fd3d0275ba97a7,
0x0707FD320C96b54182475B22a9D47b4045E74668,
0xfE2353C808F2409cCb81508005A62cef29457706,
0xE580aB95EBE6156c9717e20D513dD788B341934c,
0x4EC355d5780c9554EbdF1B40e9734A573D81052C,
0x3DdbbbB4C18f1e745A3F65ffC84E9197629Ac6B4,
0x05c0F2d1978a1Da91E5D82B8935c610b3F93f36B,
0x5221ce255906a61cf3DC2506143cd38D46A92be1,
0x573fA57407Bb0e4b761DBe801b5cbD160A8E8C21,
0x4Dacd010e15e220bC6C5C3210d166505d2b6c63A,
0x2FA26aD1BfAE9e66b5c3F364a9E8EcEc8520dB4a,
0xa357Cb3CE710a4f90fB9d56979C2C3634E3965bA,
0x1b74fcf3A084d13a9D910DB12469251988985413,
0xa948DE8A9205f1fE473490d2114c6616a90fD8d6,
0x101D5810f8841BcE68cB3e8CFbadB3f8C71fdff0,
0x9F7610115501abD147d1d82Ce92cea2A716690ED,
0xf600fd970Bc2054d81AFb1646B50531D7567b22c,
0x59cc72743488Aa24Caa92a521E74e633bb1f9096,
0x20BFFFdB086D35e1eE06b1e0Beb849eE0a0E945c,
0xa2040D6b10595EcBa2F751737b4A931A868f0655,
0x0900a13FB9382c6668a74500cccE70Eb96385e0C,
0x33d01F8BaA2319882440FE8Cf2978fb137B59Dc1,
0x7329c9ead9b5BB0AD240B75C3CFdc2828AC2EFCf,
0x77CB8c64e42ea076594A0C1E08115D8444Fa9fAc,
0x228a671629bE7a9436019AF909a1629c94bF4cAf,
0x7FF3552031C441f3F01AeDEb0C2C680FBA6dD5Df,
0x2D52F7BaE61912f7217351443eA8a226996a3Def,
0x6bac48867BC94Ff20B4C62b21d484a44D04d342C,
0xA42830eE059c77cAF8c8200B44AA9813CB0720c5,
0xf88d3412764873872aB1FdED5F168a6c1A3bF7bB,
0x3AA667D05a6aa1115cF4A533C29Bb538ACD1300c,
0xb92667E34cB6753449ADF464f18ce1833Caf26e0,
0x7BFEe91193d9Df2Ac0bFe90191D40F23c773C060,
0x1f0a6d7Db80E0C5Af146FDb836e04FAC0B1E8202,
0x2053e0218793eEc7107ec50b09B696D4431C1Ff8,
0xB8C2C00cC883d087C0Cbd443CeC51a4D04f8b147,
0xc8e99dd497ae1fc981c1dd48f49FB804FBFCB99D
];
uint256[210] airdropBalances =
[
4297396,
1728358,
1505261,
1332003,
727506,
182291,
750722,
625052,
505013,
465932,
485597,
395709,
63621,
282190,
339931,
65686,
184250,
262345,
239002,
206374,
210330,
192425,
197415,
66379,
172905,
158272,
152257,
166385,
168117,
36747,
4760,
117953,
111187,
109898,
89898,
94390,
85323,
82567,
81233,
80992,
68640,
64138,
62431,
59644,
62799,
61129,
55179,
51915,
48305,
47379,
45361,
44710,
43459,
43725,
42692,
40472,
43858,
36506,
601,
33822,
32612,
542,
31773,
28432,
21291,
25655,
25360,
25258,
23591,
23366,
23422,
21365,
20012,
19919,
19240,
19638,
18884,
17133,
16639,
15337,
14773,
14824,
14644,
12760,
12503,
9,
12208,
2092,
11859,
11672,
11192,
10321,
1629,
10303,
9539,
9200,
9115,
3925,
8894,
8531,
8399,
8151,
7665,
7634,
165,
595,
6865,
6522,
6496,
6454,
6374,
3960,
622,
5993,
5971,
5930,
5930,
5722,
5645,
123,
5105,
5040,
813,
2220,
4618,
4482,
4448,
4447,
233,
4121,
3863,
3833,
3875,
3836,
3638,
3558,
3241,
2965,
2965,
34,
2965,
2965,
2699,
2687,
139,
2372,
2130,
384,
2172,
2092,
2083,
314,
2075,
475,
1769,
1769,
1559,
1511,
1490,
1482,
248,
1361,
1251,
1245,
1180,
1180,
222,
1010,
965,
947,
889,
620,
28,
810,
767,
619,
96,
593,
494,
221,
474,
84,
320,
445,
362,
56,
331,
280,
272,
38,
34,
5,
118,
17,
89,
88,
59,
8,
1,
30,
29,
504793,
430006,
39045,
15187,
8275,
141303,
195,
113110,
82615
];
struct Airdrop {
uint256 amount;
uint256 claimed;
uint256 total_tokens;
uint256 fraction;
}
mapping(address => Airdrop) public airdrop;
mapping(address => uint256) public validated;
uint256 private airdrop_supply = 20160000 * 10 ** 18;
uint256 constant HOUR = 3600;
uint256 constant DAY = 86400;
uint256 constant WEEK = 86400 * 7;
uint256 constant YEAR = WEEK * 52;
uint256 constant RATE_TIME = WEEK;
uint256 constant INITIAL_RATE = 247_262 * 10 ** 18 / WEEK;
uint256 constant EPOCH_INFLATION = 98_831;
uint256 constant INITIAL_RATE_EPOCH_CUTTOF = 260;
uint256 public miningEpoch;
uint256 public startEpochTime;
uint256 public rate;
uint256 startEpochSupply;
event updateMiningParameters(uint256 time, uint256 rate, uint256 supply);
event Validated(address indexed investor, uint256 amount, uint256 timeStamp);
event Vested(address indexed investor, uint256 amount, uint256 timeStamp);
IERC20 public mainToken;
IVesting public vestLock;
constructor(IERC20 _mainToken, IVesting _vestLock) {
require(address(_mainToken) != address(0), "Invalid address");
require(address(_vestLock) != address(0), "Invalid address");
mainToken = _mainToken;
vestLock = _vestLock;
rate = INITIAL_RATE;
startEpochTime = block.timestamp;
mainToken.approve(address(vestLock), 2**256-1);
}
function validate() external nonReentrant {
require(msg.sender != address(0));
require(airdrop[msg.sender].amount == 0, "Already validated.");
for (uint i = 0; i < airdropArray.length; i++) {
if (airdropArray[i] == msg.sender) {
uint256 airdroppable = airdropBalances[i] * 10 ** 18;
Airdrop memory newAirdrop = Airdrop(airdroppable, 0, airdroppable, 10**18 * airdroppable / airdrop_supply);
airdrop[msg.sender] = newAirdrop;
validated[msg.sender] = 1;
emit Validated(msg.sender, airdroppable, block.timestamp);
break;
}
}
}
function claim() external nonReentrant {
require(msg.sender != address(0));
require(validated[msg.sender] == 1, "Address not validated to claim.");
require(airdrop[msg.sender].amount != 0);
uint256 avail = _available_supply();
require(avail > 0, "Nothing claimable (yet?)");
uint256 claimable = avail * airdrop[msg.sender].fraction / 10**18;
assert(claimable > 0);
if (airdrop[msg.sender].claimed != 0) {
claimable -= airdrop[msg.sender].claimed;
}
assert(airdrop[msg.sender].amount - claimable != 0);
airdrop[msg.sender].amount -= claimable;
airdrop[msg.sender].claimed += claimable;
uint256 claimable_to_send = claimable * 3 / 10;
mainToken.transfer(msg.sender, claimable_to_send);
uint256 claimable_not_yet_vested = claimable - claimable_to_send;
vestLock.vest(msg.sender, claimable_not_yet_vested, 0);
emit Vested(msg.sender, claimable, block.timestamp);
}
function claimExact(uint256 _value) external nonReentrant {
require(msg.sender != address(0));
require(airdrop[msg.sender].amount != 0);
uint256 avail = _available_supply();
uint256 claimable = avail * airdrop[msg.sender].fraction / 10**18;
if (airdrop[msg.sender].claimed != 0){
claimable -= airdrop[msg.sender].claimed;
}
require(airdrop[msg.sender].amount >= claimable);
require(_value <= claimable);
airdrop[msg.sender].amount -= _value;
airdrop[msg.sender].claimed += _value;
uint256 claimable_to_send = _value * 3 / 10;
mainToken.transfer(msg.sender, claimable_to_send);
uint256 claimable_not_yet_vested = _value - claimable_to_send;
vestLock.vest(msg.sender, claimable_not_yet_vested, 0);
emit Vested(msg.sender, _value, block.timestamp);
}
function _updateEmission() private {
if (block.timestamp >= startEpochTime + RATE_TIME) {
miningEpoch += 1;
startEpochTime = startEpochTime.add(RATE_TIME);
startEpochSupply = startEpochSupply.add(rate.mul(RATE_TIME));
if (miningEpoch < INITIAL_RATE_EPOCH_CUTTOF) {
rate = rate.mul(EPOCH_INFLATION).div(100000);
}
else {
rate = 0;
}
emit updateMiningParameters(block.timestamp, rate, startEpochSupply);
}
}
function updateEmission() public {
require(block.timestamp >= startEpochTime + RATE_TIME, "Too soon");
_updateEmission();
}
function _available_supply() private view returns(uint256) {
assert(block.timestamp - startEpochTime <= RATE_TIME);
return startEpochSupply + (block.timestamp - startEpochTime) * rate;
}
function available_supply() public view returns(uint256) {
assert(block.timestamp - startEpochTime <= RATE_TIME);
return startEpochSupply + (block.timestamp - startEpochTime) * rate;
}
} | 8,515 | 554 | 1 | 1. [H-05] Claim airdrop repeatedly
Suppose someone claims the last part of his airdrop via `claimExact()` of AirdropDistribution.sol Then airdrop\[msg.sender].amount will be set to 0.
2. [M-01] Unchecked transfers
Multiple calls to transferFrom and transfer are frequently done without checking the results. For certain ERC20 tokens, if insufficient tokens are present, no revert occurs but a result of “false” is returned.
3. [M-10] Can't claim last part of airdrop
Function `claimExact()`
Suppose you are eligible for the last part of your airdrop (or your entire airdrop if you haven't claimed anything yet). Then you call the function claim() of AirdropDistribution.sol, which has the following statement: assert(airdrop\[msg.sender].amount - claimable != 0); This statement will prevent you from claiming your airdrop because it will stop execution. | 3 |
55_MapleLoan.sol | pragma solidity ^0.8.7;
import { IERC20 } from "../modules/erc20/src/interfaces/IERC20.sol";
import { IMapleProxyFactory } from "../modules/maple-proxy-factory/contracts/interfaces/IMapleProxyFactory.sol";
import { ERC20Helper } from "../modules/erc20-helper/src/ERC20Helper.sol";
import { IMapleLoan } from "./interfaces/IMapleLoan.sol";
import { IMapleGlobalsLike } from "./interfaces/Interfaces.sol";
import { MapleLoanInternals } from "./MapleLoanInternals.sol";
contract MapleLoan is IMapleLoan, MapleLoanInternals {
modifier whenProtocolNotPaused() {
require(!isProtocolPaused(), "ML:PROTOCOL_PAUSED");
_;
}
function migrate(address migrator_, bytes calldata arguments_) external override {
require(msg.sender == _factory(), "ML:M:NOT_FACTORY");
require(_migrate(migrator_, arguments_), "ML:M:FAILED");
}
function setImplementation(address newImplementation_) external override {
require(msg.sender == _factory(), "ML:SI:NOT_FACTORY");
require(_setImplementation(newImplementation_), "ML:SI:FAILED");
}
function upgrade(uint256 toVersion_, bytes calldata arguments_) external override {
require(msg.sender == _borrower, "ML:U:NOT_BORROWER");
emit Upgraded(toVersion_, arguments_);
IMapleProxyFactory(_factory()).upgradeInstance(toVersion_, arguments_);
}
function acceptBorrower() external override {
require(msg.sender == _pendingBorrower, "ML:AB:NOT_PENDING_BORROWER");
_pendingBorrower = address(0);
emit BorrowerAccepted(_borrower = msg.sender);
}
function closeLoan(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) {
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:CL:TRANSFER_FROM_FAILED");
( principal_, interest_ ) = _closeLoan();
emit LoanClosed(principal_, interest_);
}
function drawdownFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused returns (uint256 collateralPosted_) {
require(msg.sender == _borrower, "ML:DF:NOT_BORROWER");
emit FundsDrawnDown(amount_, destination_);
uint256 additionalCollateralRequired = getAdditionalCollateralRequiredFor(amount_);
if (additionalCollateralRequired > uint256(0)) {
uint256 unaccountedCollateral = _getUnaccountedAmount(_collateralAsset);
collateralPosted_ = postCollateral(
additionalCollateralRequired > unaccountedCollateral ? additionalCollateralRequired - unaccountedCollateral : uint256(0)
);
}
_drawdownFunds(amount_, destination_);
}
function makePayment(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) {
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:MP:TRANSFER_FROM_FAILED");
( principal_, interest_ ) = _makePayment();
emit PaymentMade(principal_, interest_);
}
function postCollateral(uint256 amount_) public override whenProtocolNotPaused returns (uint256 collateralPosted_) {
require(
amount_ == uint256(0) || ERC20Helper.transferFrom(_collateralAsset, msg.sender, address(this), amount_),
"ML:PC:TRANSFER_FROM_FAILED"
);
emit CollateralPosted(collateralPosted_ = _postCollateral());
}
function proposeNewTerms(address refinancer_, bytes[] calldata calls_) external override whenProtocolNotPaused {
require(msg.sender == _borrower, "ML:PNT:NOT_BORROWER");
emit NewTermsProposed(_proposeNewTerms(refinancer_, calls_), refinancer_, calls_);
}
function removeCollateral(uint256 amount_, address destination_) external override whenProtocolNotPaused {
require(msg.sender == _borrower, "ML:RC:NOT_BORROWER");
emit CollateralRemoved(amount_, destination_);
_removeCollateral(amount_, destination_);
}
function returnFunds(uint256 amount_) public override whenProtocolNotPaused returns (uint256 fundsReturned_) {
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:RF:TRANSFER_FROM_FAILED");
emit FundsReturned(fundsReturned_ = _returnFunds());
}
function setPendingBorrower(address pendingBorrower_) external override {
require(msg.sender == _borrower, "ML:SPB:NOT_BORROWER");
emit PendingBorrowerSet(_pendingBorrower = pendingBorrower_);
}
function acceptLender() external override {
require(msg.sender == _pendingLender, "ML:AL:NOT_PENDING_LENDER");
_pendingLender = address(0);
emit LenderAccepted(_lender = msg.sender);
}
function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external override whenProtocolNotPaused {
require(msg.sender == _lender, "ML:ANT:NOT_LENDER");
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:ACT:TRANSFER_FROM_FAILED");
emit NewTermsAccepted(_acceptNewTerms(refinancer_, calls_), refinancer_, calls_);
uint256 extra = _getUnaccountedAmount(_fundsAsset);
if (extra > uint256(0)) {
emit FundsRedirected(extra, _lender);
require(ERC20Helper.transfer(_fundsAsset, _lender, extra), "ML:ANT:TRANSFER_FAILED");
}
}
function claimFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused {
require(msg.sender == _lender, "ML:CF:NOT_LENDER");
emit FundsClaimed(amount_, destination_);
_claimFunds(amount_, destination_);
}
function fundLoan(address lender_, uint256 amount_) external override whenProtocolNotPaused returns (uint256 fundsLent_) {
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:FL:TRANSFER_FROM_FAILED");
if (_nextPaymentDueDate == uint256(0)) {
emit Funded(lender_, fundsLent_ = _fundLoan(lender_), _nextPaymentDueDate);
}
uint256 extra = _getUnaccountedAmount(_fundsAsset);
if (extra > uint256(0)) {
emit FundsRedirected(extra, _lender);
require(ERC20Helper.transfer(_fundsAsset, _lender, extra), "ML:FL:TRANSFER_FAILED");
}
}
function repossess(address destination_) external override whenProtocolNotPaused returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_) {
require(msg.sender == _lender, "ML:R:NOT_LENDER");
( collateralRepossessed_, fundsRepossessed_ ) = _repossess(destination_);
emit Repossessed(collateralRepossessed_, fundsRepossessed_, destination_);
}
function setPendingLender(address pendingLender_) external override {
require(msg.sender == _lender, "ML:SPL:NOT_LENDER");
emit PendingLenderSet(_pendingLender = pendingLender_);
}
function skim(address token_, address destination_) external override whenProtocolNotPaused returns (uint256 skimmed_) {
require((msg.sender == _borrower) || (msg.sender == _lender), "L:S:NO_AUTH");
require((token_ != _fundsAsset) && (token_ != _collateralAsset), "L:S:INVALID_TOKEN");
emit Skimmed(token_, skimmed_ = IERC20(token_).balanceOf(address(this)), destination_);
require(ERC20Helper.transfer(token_, destination_, skimmed_), "L:S:TRANSFER_FAILED");
}
function getAdditionalCollateralRequiredFor(uint256 drawdown_) public view override returns (uint256 collateral_) {
uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds - drawdown_, _principalRequested, _collateralRequired);
return collateralNeeded > _collateral ? collateralNeeded - _collateral : uint256(0);
}
function getEarlyPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getEarlyPaymentBreakdown();
}
function getNextPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getNextPaymentBreakdown();
}
function isProtocolPaused() public view override returns (bool paused_) {
return IMapleGlobalsLike(IMapleProxyFactory(_factory()).mapleGlobals()).protocolPaused();
}
function borrower() external view override returns (address borrower_) {
return _borrower;
}
function claimableFunds() external view override returns (uint256 claimableFunds_) {
return _claimableFunds;
}
function collateral() external view override returns (uint256 collateral_) {
return _collateral;
}
function collateralAsset() external view override returns (address collateralAsset_) {
return _collateralAsset;
}
function collateralRequired() external view override returns (uint256 collateralRequired_) {
return _collateralRequired;
}
function drawableFunds() external view override returns (uint256 drawableFunds_) {
return _drawableFunds;
}
function earlyFeeRate() external view override returns (uint256 earlyFeeRate_) {
return _earlyFeeRate;
}
function endingPrincipal() external view override returns (uint256 endingPrincipal_) {
return _endingPrincipal;
}
function excessCollateral() external view override returns (uint256 excessCollateral_) {
uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds, _principalRequested, _collateralRequired);
return _collateral > collateralNeeded ? _collateral - collateralNeeded : uint256(0);
}
function factory() external view override returns (address factory_) {
return _factory();
}
function fundsAsset() external view override returns (address fundsAsset_) {
return _fundsAsset;
}
function gracePeriod() external view override returns (uint256 gracePeriod_) {
return _gracePeriod;
}
function implementation() external view override returns (address implementation_) {
return _implementation();
}
function interestRate() external view override returns (uint256 interestRate_) {
return _interestRate;
}
function lateFeeRate() external view override returns (uint256 lateFeeRate_) {
return _lateFeeRate;
}
function lateInterestPremium() external view override returns (uint256 lateInterestPremium_) {
return _lateInterestPremium;
}
function lender() external view override returns (address lender_) {
return _lender;
}
function nextPaymentDueDate() external view override returns (uint256 nextPaymentDueDate_) {
return _nextPaymentDueDate;
}
function paymentInterval() external view override returns (uint256 paymentInterval_) {
return _paymentInterval;
}
function paymentsRemaining() external view override returns (uint256 paymentsRemaining_) {
return _paymentsRemaining;
}
function pendingBorrower() external view override returns (address pendingBorrower_) {
return _pendingBorrower;
}
function pendingLender() external view override returns (address pendingLender_) {
return _pendingLender;
}
function principalRequested() external view override returns (uint256 principalRequested_) {
return _principalRequested;
}
function principal() external view override returns (uint256 principal_) {
return _principal;
}
function superFactory() external view override returns (address superFactory_) {
return _factory();
}
} | 2,616 | 212 | 2 | 1. [H-01] makePayment() Lack of access control allows malicious lender to retrieve a large portion of the funds earlier, making the borrower suffer fund loss (Lack of access control)
2. [M-01] Anyone can call `closeLoan()` to close the loan (Access control) | 2 |
57_Zap.sol | pragma solidity 0.6.11;
import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
import {ProxyAdmin} from "@openzeppelin/contracts/proxy/ProxyAdmin.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20, SafeMath} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {AccessControlDefendedBase} from "./common/AccessControlDefended.sol";
import {ISett} from "./interfaces/ISett.sol";
import {IBadgerSettPeak, IByvWbtcPeak} from "./interfaces/IPeak.sol";
import {IbBTC} from "./interfaces/IbBTC.sol";
import {IbyvWbtc} from "./interfaces/IbyvWbtc.sol";
contract Zap is Initializable, Pausable, AccessControlDefendedBase {
using SafeERC20 for IERC20;
using SafeMath for uint;
IBadgerSettPeak public constant settPeak = IBadgerSettPeak(0x41671BA1abcbA387b9b2B752c205e22e916BE6e3);
IByvWbtcPeak public constant byvWbtcPeak = IByvWbtcPeak(0x825218beD8BE0B30be39475755AceE0250C50627);
IERC20 public constant ibbtc = IERC20(0xc4E15973E6fF2A35cC804c2CF9D2a1b817a8b40F);
IERC20 public constant ren = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D);
IERC20 public constant wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
IController public constant controller = IController(0x63cF44B2548e4493Fd099222A1eC79F3344D9682);
struct Pool {
IERC20 lpToken;
ICurveFi deposit;
ISett sett;
}
Pool[4] public pools;
address public governance;
modifier onlyGovernance() {
require(governance == msg.sender, "NOT_OWNER");
_;
}
function init(address _governance) initializer external {
_setGovernance(_governance);
pools[0] = Pool({
lpToken: IERC20(0x49849C98ae39Fff122806C06791Fa73784FB3675),
deposit: ICurveFi(0x93054188d876f558f4a66B2EF1d97d16eDf0895B),
sett: ISett(0x6dEf55d2e18486B9dDfaA075bc4e4EE0B28c1545)
});
pools[1] = Pool({
lpToken: IERC20(0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3),
deposit: ICurveFi(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714),
sett: ISett(0xd04c48A53c111300aD41190D63681ed3dAd998eC)
});
pools[2] = Pool({
lpToken: IERC20(0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd),
deposit: ICurveFi(0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c),
sett: ISett(0xb9D076fDe463dbc9f915E5392F807315Bf940334)
});
pools[3] = Pool({
lpToken: wbtc,
deposit: ICurveFi(0x0),
sett: ISett(0x4b92d19c11435614CD49Af1b589001b7c08cD4D5)
});
for (uint i = 0; i < pools.length; i++) {
Pool memory pool = pools[i];
pool.lpToken.safeApprove(address(pool.sett), uint(-1));
if (i < 3) {
ren.safeApprove(address(pool.deposit), uint(-1));
wbtc.safeApprove(address(pool.deposit), uint(-1));
IERC20(address(pool.sett)).safeApprove(address(settPeak), uint(-1));
} else {
IERC20(address(pool.sett)).safeApprove(address(byvWbtcPeak), uint(-1));
}
}
pools[2].lpToken.safeApprove(address(pools[2].deposit), uint(-1));
}
function mint(IERC20 token, uint amount, uint poolId, uint idx, uint minOut)
external
defend
blockLocked
whenNotPaused
returns(uint _ibbtc)
{
token.safeTransferFrom(msg.sender, address(this), amount);
Pool memory pool = pools[poolId];
if (poolId < 3) {
_addLiquidity(pool.deposit, amount, poolId + 2, idx);
pool.sett.deposit(pool.lpToken.balanceOf(address(this)));
_ibbtc = settPeak.mint(poolId, pool.sett.balanceOf(address(this)), new bytes32[](0));
} else if (poolId == 3) {
IbyvWbtc(address(pool.sett)).deposit(new bytes32[](0));
_ibbtc = byvWbtcPeak.mint(pool.sett.balanceOf(address(this)), new bytes32[](0));
} else {
revert("INVALID_POOL_ID");
}
require(_ibbtc >= minOut, "INSUFFICIENT_IBBTC");
ibbtc.safeTransfer(msg.sender, _ibbtc);
}
function _addLiquidity(ICurveFi pool, uint amount, uint numTokens, uint idx) internal {
if (numTokens == 2) {
uint[2] memory amounts;
amounts[idx] = amount;
pool.add_liquidity(amounts, 0);
}
if (numTokens == 3) {
uint[3] memory amounts;
amounts[idx] = amount;
pool.add_liquidity(amounts, 0);
}
if (numTokens == 4) {
uint[4] memory amounts;
amounts[idx] = amount;
pool.add_liquidity(amounts, 0);
}
}
function calcMint(address token, uint amount) external view returns(uint poolId, uint idx, uint bBTC, uint fee) {
if (token == address(ren)) {
return calcMintWithRen(amount);
}
if (token == address(wbtc)) {
return calcMintWithWbtc(amount);
}
revert("INVALID_TOKEN");
}
function calcMintWithRen(uint amount) public view returns(uint poolId, uint idx, uint bBTC, uint fee) {
uint _ibbtc;
uint _fee;
(bBTC, fee) = curveLPToIbbtc(0, pools[0].deposit.calc_token_amount([amount,0], true));
}
function calcMintWithWbtc(uint amount) public view returns(uint poolId, uint idx, uint bBTC, uint fee) {
uint _ibbtc;
uint _fee;
(bBTC, fee) = curveLPToIbbtc(0, pools[0].deposit.calc_token_amount([0,amount], true));
idx = 1;
}
function curveLPToIbbtc(uint poolId, uint _lp) public view returns(uint bBTC, uint fee) {
Pool memory pool = pools[poolId];
uint _sett = _lp.mul(1e18).div(pool.sett.getPricePerFullShare());
return settPeak.calcMint(poolId, _sett);
}
function redeem(IERC20 token, uint amount, uint poolId, int128 idx, uint minOut)
external
defend
blockLocked
whenNotPaused
returns(uint out)
{
ibbtc.safeTransferFrom(msg.sender, address(this), amount);
Pool memory pool = pools[poolId];
if (poolId < 3) {
settPeak.redeem(poolId, amount);
pool.sett.withdrawAll();
pool.deposit.remove_liquidity_one_coin(pool.lpToken.balanceOf(address(this)), idx, minOut);
} else if (poolId == 3) {
byvWbtcPeak.redeem(amount);
IbyvWbtc(address(pool.sett)).withdraw();
} else {
revert("INVALID_POOL_ID");
}
out = token.balanceOf(address(this));
token.safeTransfer(msg.sender, out);
}
function calcRedeem(address token, uint amount) external view returns(uint poolId, uint idx, uint out, uint fee) {
if (token == address(ren)) {
return calcRedeemInRen(amount);
}
if (token == address(wbtc)) {
return calcRedeemInWbtc(amount);
}
revert("INVALID_TOKEN");
}
function calcRedeemInRen(uint amount) public view returns(uint poolId, uint idx, uint renAmount, uint fee) {
uint _lp;
uint _fee;
uint _ren;
(_lp, fee) = ibbtcToCurveLP(0, amount);
renAmount = pools[0].deposit.calc_withdraw_one_coin(_lp, 0);
}
function calcRedeemInWbtc(uint amount) public view returns(uint poolId, uint idx, uint wBTCAmount, uint fee) {
uint _lp;
uint _fee;
uint _wbtc;
(_lp, fee) = ibbtcToCurveLP(0, amount);
wBTCAmount = pools[0].deposit.calc_withdraw_one_coin(_lp, 1);
idx = 1;
}
function ibbtcToCurveLP(uint poolId, uint bBtc) public view returns(uint lp, uint fee) {
uint sett;
uint max;
(sett,fee,max) = settPeak.calcRedeem(poolId, bBtc);
Pool memory pool = pools[poolId];
if (bBtc > max) {
return (0,fee);
} else {
uint strategyFee = sett.mul(controller.strategies(pool.lpToken).withdrawalFee()).div(10000);
lp = sett.sub(strategyFee).mul(pool.sett.getPricePerFullShare()).div(1e18);
fee = fee.add(strategyFee);
}
}
function setGovernance(address _governance) external onlyGovernance {
_setGovernance(_governance);
}
function _setGovernance(address _governance) internal {
require(_governance != address(0), "NULL_ADDRESS");
governance = _governance;
}
function approveContractAccess(address account) external onlyGovernance {
_approveContractAccess(account);
}
function revokeContractAccess(address account) external onlyGovernance {
_revokeContractAccess(account);
}
function pause() external onlyGovernance {
_pause();
}
function unpause() external onlyGovernance {
_unpause();
}
}
interface ICurveFi {
function add_liquidity(uint[2] calldata amounts, uint min_mint_amount) external;
function calc_token_amount(uint[2] calldata amounts, bool isDeposit) external view returns(uint);
function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external;
function calc_token_amount(uint[3] calldata amounts, bool isDeposit) external view returns(uint);
function add_liquidity(uint[4] calldata amounts, uint min_mint_amount) external;
function calc_token_amount(uint[4] calldata amounts, bool isDeposit) external view returns(uint);
function remove_liquidity_one_coin(uint _token_amount, int128 i, uint min_amount) external;
function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns(uint);
}
interface IStrategy {
function withdrawalFee() external view returns(uint);
}
interface IController {
function strategies(IERC20 token) external view returns(IStrategy);
} | 2,784 | 226 | 0 | 1. [M-01] Improper implementation of slippage check (Lack of Slippage Protection)
Function `redeem()`
2. [M-03] Zap contract's redeem() function doesn't check which token the user wants to receive
(Lack of input validation) | 2 |
59_UniswapHandler.sol | pragma solidity >=0.6.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import '@uniswap/lib/contracts/libraries/Babylonian.sol';
import '@uniswap/lib/contracts/libraries/FullMath.sol';
import "../Permissions.sol";
import "../libraries/UniswapV2Library.sol";
contract UniswapHandler is Initializable, Permissions {
using SafeMath for uint256;
using SafeERC20 for ERC20;
bytes32 public constant BUYER_ROLE = keccak256("BUYER_ROLE");
ERC20 public malt;
ERC20 public rewardToken;
ERC20 public lpToken;
IUniswapV2Router02 public router;
address public uniswapV2Factory;
address[] public buyers;
mapping(address => bool) public buyersActive;
event AddMaltBuyer(address buyer);
event RemoveMaltBuyer(address buyer);
function initialize(
address _timelock,
address initialAdmin,
address _maltToken,
address _rewardToken,
address _lpToken,
address _router,
address _uniswapV2Factory
) external initializer {
_adminSetup(_timelock);
_setupRole(ADMIN_ROLE, initialAdmin);
_setRoleAdmin(BUYER_ROLE, ADMIN_ROLE);
malt = ERC20(_maltToken);
rewardToken = ERC20(_rewardToken);
router = IUniswapV2Router02(_router);
lpToken = ERC20(_lpToken);
uniswapV2Factory = _uniswapV2Factory;
}
function calculateMintingTradeSize(uint256 priceTarget) external view returns (uint256) {
return _calculateTradeSize(address(malt), address(rewardToken), priceTarget);
}
function calculateBurningTradeSize(uint256 priceTarget) external view returns (uint256) {
return _calculateTradeSize(address(rewardToken), address(malt), priceTarget);
}
function reserves() public view returns (uint256 maltSupply, uint256 rewardSupply) {
(maltSupply, rewardSupply) = UniswapV2Library.getReserves(
uniswapV2Factory,
address(malt),
address(rewardToken)
);
}
function maltMarketPrice() public view returns (uint256 price, uint256 decimals) {
(uint256 maltReserves, uint256 rewardReserves) = UniswapV2Library.getReserves(
uniswapV2Factory,
address(malt),
address(rewardToken)
);
if (maltReserves == 0 || rewardReserves == 0) {
price = 0;
decimals = 18;
return (price, decimals);
}
uint256 rewardDecimals = rewardToken.decimals();
uint256 maltDecimals = malt.decimals();
if (rewardDecimals > maltDecimals) {
uint256 diff = rewardDecimals - maltDecimals;
price = rewardReserves.mul(10**rewardDecimals).div(maltReserves.mul(10**diff));
decimals = rewardDecimals;
} else if (rewardDecimals < maltDecimals) {
uint256 diff = maltDecimals - rewardDecimals;
price = (rewardReserves.mul(10**diff)).mul(10**rewardDecimals).div(maltReserves);
decimals = maltDecimals;
} else {
price = rewardReserves.mul(10**rewardDecimals).div(maltReserves);
decimals = rewardDecimals;
}
}
function getOptimalLiquidity(address tokenA, address tokenB, uint256 liquidityB)
external view returns (uint256 liquidityA)
{
(uint256 reservesA, uint256 reservesB) = UniswapV2Library.getReserves(
uniswapV2Factory,
tokenA,
tokenB
);
liquidityA = UniswapV2Library.quote(
liquidityB,
reservesB,
reservesA
);
}
function buyMalt()
external
onlyRole(BUYER_ROLE, "Must have buyer privs")
returns (uint256 purchased)
{
uint256 rewardBalance = rewardToken.balanceOf(address(this));
if (rewardBalance == 0) {
return 0;
}
rewardToken.approve(address(router), rewardBalance);
address[] memory path = new address[](2);
path[0] = address(rewardToken);
path[1] = address(malt);
router.swapExactTokensForTokens(
rewardBalance,
0,
path,
address(this),
now
);
purchased = malt.balanceOf(address(this));
malt.safeTransfer(msg.sender, purchased);
}
function sellMalt() external returns (uint256 rewards) {
uint256 maltBalance = malt.balanceOf(address(this));
if (maltBalance == 0) {
return 0;
}
malt.approve(address(router), maltBalance);
address[] memory path = new address[](2);
path[0] = address(malt);
path[1] = address(rewardToken);
router.swapExactTokensForTokens(
maltBalance,
0,
path,
address(this),
now
);
rewards = rewardToken.balanceOf(address(this));
rewardToken.safeTransfer(msg.sender, rewards);
}
function addLiquidity() external returns (
uint256 maltUsed,
uint256 rewardUsed,
uint256 liquidityCreated
) {
uint256 maltBalance = malt.balanceOf(address(this));
uint256 rewardBalance = rewardToken.balanceOf(address(this));
if (maltBalance == 0 || rewardBalance == 0) {
return (0, 0, 0);
}
rewardToken.approve(address(router), rewardBalance);
malt.approve(address(router), maltBalance);
(maltUsed, rewardUsed, liquidityCreated) = router.addLiquidity(
address(malt),
address(rewardToken),
maltBalance,
rewardBalance,
maltBalance.mul(95).div(100),
rewardBalance.mul(95).div(100),
msg.sender,
now
);
if (maltUsed < maltBalance) {
malt.safeTransfer(msg.sender, maltBalance.sub(maltUsed));
}
if (rewardUsed < rewardBalance) {
rewardToken.safeTransfer(msg.sender, rewardBalance.sub(rewardUsed));
}
}
function removeLiquidity() external returns (uint256 amountMalt, uint256 amountReward) {
uint256 liquidityBalance = lpToken.balanceOf(address(this));
if (liquidityBalance == 0) {
return (0, 0);
}
lpToken.approve(address(router), liquidityBalance);
(amountMalt, amountReward) = router.removeLiquidity(
address(malt),
address(rewardToken),
liquidityBalance,
0,
0,
msg.sender,
now
);
if (amountMalt == 0 || amountReward == 0) {
liquidityBalance = lpToken.balanceOf(address(this));
lpToken.safeTransfer(msg.sender, liquidityBalance);
return (amountMalt, amountReward);
}
}
function _calculateTradeSize(address sellToken, address buyToken, uint256 priceTarget) private view returns (uint256) {
(uint256 sellReserves, uint256 buyReserves) = UniswapV2Library.getReserves(
uniswapV2Factory,
sellToken,
buyToken
);
uint256 invariant = sellReserves.mul(buyReserves);
uint256 buyBase = 10**uint256(ERC20(buyToken).decimals());
uint256 leftSide = Babylonian.sqrt(
FullMath.mulDiv(
invariant.mul(1000),
priceTarget,
buyBase.div(priceTarget).mul(buyBase).mul(997)
)
);
uint256 rightSide = sellReserves.mul(1000).div(997);
if (leftSide < rightSide) return 0;
return leftSide.sub(rightSide);
}
function addNewBuyer(address _buyer)
external
onlyRole(ADMIN_ROLE, "Must have admin role")
notSameBlock
{
require(_buyer != address(0), "Cannot use address 0");
if (buyersActive[_buyer]) {
return;
}
buyersActive[_buyer] = true;
buyers.push(_buyer);
_setupRole(BUYER_ROLE, _buyer);
emit AddMaltBuyer(_buyer);
}
function removeBuyer(address _buyer)
external
onlyRole(ADMIN_ROLE, "Must have admin role")
notSameBlock
{
if (buyers.length == 0 || !buyersActive[_buyer]) {
return;
}
address buyer;
buyersActive[_buyer] = false;
emit RemoveMaltBuyer(_buyer);
revokeRole(BUYER_ROLE, _buyer);
for (uint i = 0; i < buyers.length - 1; i = i + 1) {
if (buyers[i] == _buyer) {
buyers[i] = buyers[buyers.length - 1];
buyers.pop();
return;
}
}
buyers.pop();
}
} | 2,078 | 241 | 1 | 1. [M-09] UniswapHandler.maltMarketPrice() returns wrong decimals (Uncheck return values)
The UniswapHandler.maltMarketPrice function returns a tuple of the price and the decimals of the price. However, the returned decimals do not match the computed price for the else if (rewardDecimals < maltDecimals) branch
2. [M-23] `addLiquidity()` Does Not Reset Approval If Not All Tokens Were Added To Liquidity Pool | 2 |
61_SavingsAccountUtil.sol | pragma solidity 0.7.6;
import '../interfaces/ISavingsAccount.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
library SavingsAccountUtil {
using SafeERC20 for IERC20;
function depositFromSavingsAccount(
ISavingsAccount _savingsAccount,
address _from,
address _to,
uint256 _amount,
address _token,
address _strategy,
bool _withdrawShares,
bool _toSavingsAccount
) internal returns (uint256) {
if (_toSavingsAccount) {
return savingsAccountTransfer(_savingsAccount, _from, _to, _amount, _token, _strategy);
} else {
return withdrawFromSavingsAccount(_savingsAccount, _from, _to, _amount, _token, _strategy, _withdrawShares);
}
}
function directDeposit(
ISavingsAccount _savingsAccount,
address _from,
address _to,
uint256 _amount,
address _token,
bool _toSavingsAccount,
address _strategy
) internal returns (uint256) {
if (_toSavingsAccount) {
return directSavingsAccountDeposit(_savingsAccount, _from, _to, _amount, _token, _strategy);
} else {
return transferTokens(_token, _amount, _from, _to);
}
}
function directSavingsAccountDeposit(
ISavingsAccount _savingsAccount,
address _from,
address _to,
uint256 _amount,
address _token,
address _strategy
) internal returns (uint256 _sharesReceived) {
transferTokens(_token, _amount, _from, address(this));
uint256 _ethValue;
if (_token == address(0)) {
_ethValue = _amount;
} else {
address _approveTo = _strategy;
if (_strategy == address(0)) {
_approveTo = address(_savingsAccount);
}
IERC20(_token).safeApprove(_approveTo, _amount);
}
_sharesReceived = _savingsAccount.deposit{value: _ethValue}(_amount, _token, _strategy, _to);
}
function savingsAccountTransfer(
ISavingsAccount _savingsAccount,
address _from,
address _to,
uint256 _amount,
address _token,
address _strategy
) internal returns (uint256) {
if (_from == address(this)) {
_savingsAccount.transfer(_amount, _token, _strategy, _to);
} else {
_savingsAccount.transferFrom(_amount, _token, _strategy, _from, _to);
}
return _amount;
}
function withdrawFromSavingsAccount(
ISavingsAccount _savingsAccount,
address _from,
address _to,
uint256 _amount,
address _token,
address _strategy,
bool _withdrawShares
) internal returns (uint256 _amountReceived) {
if (_from == address(this)) {
_amountReceived = _savingsAccount.withdraw(_amount, _token, _strategy, payable(_to), _withdrawShares);
} else {
_amountReceived = _savingsAccount.withdrawFrom(_amount, _token, _strategy, _from, payable(_to), _withdrawShares);
}
}
function transferTokens(
address _token,
uint256 _amount,
address _from,
address _to
) internal returns (uint256) {
if (_amount == 0) {
return 0;
}
if (_token == address(0)) {
require(msg.value >= _amount, 'ethers provided should be greater than _amount');
if (_to != address(this)) {
(bool success, ) = payable(_to).call{value: _amount}('');
require(success, 'Transfer failed');
}
if (msg.value > _amount) {
(bool success, ) = payable(address(msg.sender)).call{value: msg.value - _amount}('');
require(success, 'Transfer failed');
}
return _amount;
}
if (_from == address(this)) {
IERC20(_token).safeTransfer(_to, _amount);
} else {
IERC20(_token).safeTransferFrom(_from, _to, _amount);
}
return _amount;
}
} | null | null | 1 | 1. [H-02] Wrong returns of `SavingsAccountUtil.depositFromSavingsAccount()` can cause fund loss (Unchecked Return Values)
The function SavingsAccountUtil.depositFromSavingsAccount() is expected to return the number of equivalent shares for given _asset. However, since `savingsAccountTransfer()` does not return the result of _savingsAccount.transfer(), but returned _amount instead, which means that SavingsAccountUtil.depositFromSavingsAccount() may not return the actual shares (when pps is not 1).
2. [H-03] denial of service (Misuse of `msg.value`)
It is wrong to use `msg.value` in `transferTokens` because it'll be the msg.value of the calling function. therefore every transfer of ether using this function is wrong and dangerous, the solution is to remove all msg.value from this function and just transfer _amount regularly.
| 2 |
61_SavingsAccount.sol | pragma solidity 0.7.6;
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '../interfaces/ISavingsAccount.sol';
import '../interfaces/IStrategyRegistry.sol';
import '../interfaces/IYield.sol';
contract SavingsAccount is ISavingsAccount, Initializable, OwnableUpgradeable, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public strategyRegistry;
address public creditLine;
mapping(address => mapping(address => mapping(address => uint256))) public override balanceInShares;
mapping(address => mapping(address => mapping(address => uint256))) public allowance;
modifier onlyCreditLine(address _caller) {
require(_caller == creditLine, 'Invalid caller');
_;
}
function initialize(
address _owner,
address _strategyRegistry,
address _creditLine
) external initializer {
__Ownable_init();
super.transferOwnership(_owner);
_updateCreditLine(_creditLine);
_updateStrategyRegistry(_strategyRegistry);
}
function updateCreditLine(address _creditLine) external onlyOwner {
_updateCreditLine(_creditLine);
}
function _updateCreditLine(address _creditLine) internal {
require(_creditLine != address(0), 'SavingsAccount::initialize zero address');
creditLine = _creditLine;
emit CreditLineUpdated(_creditLine);
}
function updateStrategyRegistry(address _strategyRegistry) external onlyOwner {
_updateStrategyRegistry(_strategyRegistry);
}
function _updateStrategyRegistry(address _strategyRegistry) internal {
require(_strategyRegistry != address(0), 'SavingsAccount::updateStrategyRegistry zero address');
strategyRegistry = _strategyRegistry;
emit StrategyRegistryUpdated(_strategyRegistry);
}
function deposit(
uint256 _amount,
address _token,
address _strategy,
address _to
) external payable override nonReentrant returns (uint256) {
require(_to != address(0), 'SavingsAccount::deposit receiver address should not be zero address');
uint256 _sharesReceived = _deposit(_amount, _token, _strategy);
balanceInShares[_to][_token][_strategy] = balanceInShares[_to][_token][_strategy].add(_sharesReceived);
emit Deposited(_to, _sharesReceived, _token, _strategy);
return _sharesReceived;
}
function _deposit(
uint256 _amount,
address _token,
address _strategy
) internal returns (uint256 _sharesReceived) {
require(_amount != 0, 'SavingsAccount::_deposit Amount must be greater than zero');
_sharesReceived = _depositToYield(_amount, _token, _strategy);
}
function _depositToYield(
uint256 _amount,
address _token,
address _strategy
) internal returns (uint256 _sharesReceived) {
require(IStrategyRegistry(strategyRegistry).registry(_strategy), 'SavingsAccount::deposit strategy do not exist');
uint256 _ethValue;
if (_token == address(0)) {
_ethValue = _amount;
require(msg.value == _amount, 'SavingsAccount::deposit ETH sent must be equal to amount');
}
_sharesReceived = IYield(_strategy).lockTokens{value: _ethValue}(msg.sender, _token, _amount);
}
function switchStrategy(
uint256 _amount,
address _token,
address _currentStrategy,
address _newStrategy
) external override nonReentrant {
require(_currentStrategy != _newStrategy, 'SavingsAccount::switchStrategy Same strategy');
require(IStrategyRegistry(strategyRegistry).registry(_newStrategy), 'SavingsAccount::_newStrategy do not exist');
require(_amount != 0, 'SavingsAccount::switchStrategy Amount must be greater than zero');
_amount = IYield(_currentStrategy).getSharesForTokens(_amount, _token);
balanceInShares[msg.sender][_token][_currentStrategy] = balanceInShares[msg.sender][_token][_currentStrategy].sub(
_amount,
'SavingsAccount::switchStrategy Insufficient balance'
);
uint256 _tokensReceived = IYield(_currentStrategy).unlockTokens(_token, _amount);
uint256 _ethValue;
if (_token != address(0)) {
IERC20(_token).safeApprove(_newStrategy, _tokensReceived);
} else {
_ethValue = _tokensReceived;
}
_amount = _tokensReceived;
uint256 _sharesReceived = IYield(_newStrategy).lockTokens{value: _ethValue}(address(this), _token, _tokensReceived);
balanceInShares[msg.sender][_token][_newStrategy] = balanceInShares[msg.sender][_token][_newStrategy].add(_sharesReceived);
emit StrategySwitched(msg.sender, _token, _amount, _sharesReceived, _currentStrategy, _newStrategy);
}
function withdraw(
uint256 _amount,
address _token,
address _strategy,
address payable _to,
bool _withdrawShares
) external override nonReentrant returns (uint256) {
require(_amount != 0, 'SavingsAccount::withdraw Amount must be greater than zero');
_amount = IYield(_strategy).getSharesForTokens(_amount, _token);
balanceInShares[msg.sender][_token][_strategy] = balanceInShares[msg.sender][_token][_strategy].sub(
_amount,
'SavingsAccount::withdraw Insufficient amount'
);
(address _receivedToken, uint256 _amountReceived) = _withdraw(_amount, _token, _strategy, _to, _withdrawShares);
emit Withdrawn(msg.sender, _to, _amount, _token, _strategy, _withdrawShares);
return _amountReceived;
}
function withdrawFrom(
uint256 _amount,
address _token,
address _strategy,
address _from,
address payable _to,
bool _withdrawShares
) external override nonReentrant returns (uint256) {
require(_amount != 0, 'SavingsAccount::withdrawFrom Amount must be greater than zero');
allowance[_from][_token][msg.sender] = allowance[_from][_token][msg.sender].sub(
_amount,
'SavingsAccount::withdrawFrom allowance limit exceeding'
);
_amount = IYield(_strategy).getSharesForTokens(_amount, _token);
balanceInShares[_from][_token][_strategy] = balanceInShares[_from][_token][_strategy].sub(
_amount,
'SavingsAccount::withdrawFrom insufficient balance'
);
(address _receivedToken, uint256 _amountReceived) = _withdraw(_amount, _token, _strategy, _to, _withdrawShares);
emit Withdrawn(_from, msg.sender, _amount, _token, _strategy, _withdrawShares);
return _amountReceived;
}
function _withdraw(
uint256 _amount,
address _token,
address _strategy,
address payable _to,
bool _withdrawShares
) internal returns (address _tokenReceived, uint256 _amountReceived) {
if (_withdrawShares) {
_tokenReceived = IYield(_strategy).liquidityToken(_token);
require(_tokenReceived != address(0), 'Liquidity Tokens address cannot be address(0)');
_amountReceived = IYield(_strategy).unlockShares(_tokenReceived, _amount);
} else {
_tokenReceived = _token;
_amountReceived = IYield(_strategy).unlockTokens(_token, _amount);
}
_transfer(_amountReceived, _tokenReceived, _to);
}
function _transfer(
uint256 _amount,
address _token,
address payable _to
) internal {
if (_token == address(0)) {
(bool _success, ) = _to.call{value: _amount}('');
require(_success, 'Transfer failed');
} else {
IERC20(_token).safeTransfer(_to, _amount);
}
}
function withdrawAll(address _token) external override nonReentrant returns (uint256 _tokenReceived) {
address[] memory _strategyList = IStrategyRegistry(strategyRegistry).getStrategies();
for (uint256 i = 0; i < _strategyList.length; i++) {
if (balanceInShares[msg.sender][_token][_strategyList[i]] != 0 && _strategyList[i] != address(0)) {
uint256 _amount = balanceInShares[msg.sender][_token][_strategyList[i]];
_amount = IYield(_strategyList[i]).unlockTokens(_token, balanceInShares[msg.sender][_token][_strategyList[i]]);
_tokenReceived = _tokenReceived.add(_amount);
delete balanceInShares[msg.sender][_token][_strategyList[i]];
}
}
if (_tokenReceived == 0) return 0;
_transfer(_tokenReceived, _token, payable(msg.sender));
emit WithdrawnAll(msg.sender, _tokenReceived, _token);
}
function withdrawAll(address _token, address _strategy) external override nonReentrant returns (uint256 _tokenReceived) {
uint256 _sharesBalance = balanceInShares[msg.sender][_token][_strategy];
if(_sharesBalance == 0) return 0;
uint256 _amount = IYield(_strategy).unlockTokens(_token, _sharesBalance);
delete balanceInShares[msg.sender][_token][_strategy];
_transfer(_amount, _token, payable(msg.sender));
emit Withdrawn(msg.sender, msg.sender, _amount, _token, _strategy, false);
}
function approve(
uint256 _amount,
address _token,
address _to
) external override {
allowance[msg.sender][_token][_to] = _amount;
emit Approved(_token, msg.sender, _to, _amount);
}
function increaseAllowance(
uint256 _amount,
address _token,
address _to
) external override {
uint256 _updatedAllowance = allowance[msg.sender][_token][_to].add(_amount);
allowance[msg.sender][_token][_to] = _updatedAllowance;
emit Approved(_token, msg.sender, _to, _updatedAllowance);
}
function decreaseAllowance(
uint256 _amount,
address _token,
address _to
) external override {
uint256 _updatedAllowance = allowance[msg.sender][_token][_to].sub(_amount);
allowance[msg.sender][_token][_to] = _updatedAllowance;
emit Approved(_token, msg.sender, _to, _updatedAllowance);
}
function increaseAllowanceToCreditLine(
uint256 _amount,
address _token,
address _from
) external override onlyCreditLine(msg.sender) {
allowance[_from][_token][msg.sender] = allowance[_from][_token][msg.sender].add(_amount);
emit CreditLineAllowanceRefreshed(_token, _from, msg.sender, _amount);
}
function transfer(
uint256 _amount,
address _token,
address _strategy,
address _to
) external override returns (uint256) {
require(_amount != 0, 'SavingsAccount::transfer zero amount');
if (_strategy != address(0)) {
_amount = IYield(_strategy).getSharesForTokens(_amount, _token);
}
balanceInShares[msg.sender][_token][_strategy] = balanceInShares[msg.sender][_token][_strategy].sub(
_amount,
'SavingsAccount::transfer insufficient funds'
);
balanceInShares[_to][_token][_strategy] = balanceInShares[_to][_token][_strategy].add(_amount);
emit Transfer(_token, _strategy, msg.sender, _to, _amount);
return _amount;
}
function transferFrom(
uint256 _amount,
address _token,
address _strategy,
address _from,
address _to
) external override returns (uint256) {
require(_amount != 0, 'SavingsAccount::transferFrom zero amount');
allowance[_from][_token][msg.sender] = allowance[_from][_token][msg.sender].sub(
_amount,
'SavingsAccount::transferFrom allowance limit exceeding'
);
if (_strategy != address(0)) {
_amount = IYield(_strategy).getSharesForTokens(_amount, _token);
}
balanceInShares[_from][_token][_strategy] = balanceInShares[_from][_token][_strategy].sub(
_amount,
'SavingsAccount::transferFrom insufficient allowance'
);
balanceInShares[_to][_token][_strategy] = (balanceInShares[_to][_token][_strategy]).add(_amount);
emit Transfer(_token, _strategy, _from, _to, _amount);
return _amount;
}
function getTotalTokens(address _user, address _token) external override returns (uint256 _totalTokens) {
address[] memory _strategyList = IStrategyRegistry(strategyRegistry).getStrategies();
for (uint256 i = 0; i < _strategyList.length; i++) {
uint256 _liquidityShares = balanceInShares[_user][_token][_strategyList[i]];
if (_liquidityShares != 0) {
uint256 _tokenInStrategy = _liquidityShares;
if (_strategyList[i] != address(0)) {
_tokenInStrategy = IYield(_strategyList[i]).getTokensForShares(_liquidityShares, _token);
}
_totalTokens = _totalTokens.add(_tokenInStrategy);
}
}
}
receive() external payable {}
} | 2,996 | 285 | 0 | 1. [H-07] SavingsAccount `withdrawAll()` and `switchStrategy()` can freeze user funds by ignoring possible strategy liquidity issues
Full withdrawal and moving funds between strategies can lead to wrong accounting if the corresponding market has tight liquidity, which can be the case at least for AaveYield. That is, as the whole amount is required to be moved at once from Aave, both `withdrawAll()` and `switchStrategy()` will incorrectly account for partial withdrawal as if it was full whenever the corresponding underlying yield pool had liquidity issues.
2. [H-08] Possibility to drain SavingsAccount contract assets (Steal Tokens)
A malicious actor can manipulate `switchStrategy()` function in a way to withdraw tokens that are locked in SavingsAccount contract (the risk severity should be reviewed) | 2 |
Subsets and Splits