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 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 6