// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
contract Governable {
address public gov;
constructor() public {
gov = msg.sender;
}
modifier onlyGov() {
require(msg.sender == gov, "Governable: forbidden");
_;
}
function setGov(address _gov) external onlyGov {
gov = _gov;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IExternalHandler {
function makeExternalCalls(
address[] memory targets,
bytes[] memory dataList,
address[] memory refundTokens,
address[] memory refundReceivers
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IVault.sol";
interface IGlpManager {
function glp() external view returns (address);
function usdg() external view returns (address);
function vault() external view returns (IVault);
function cooldownDuration() external returns (uint256);
function getAumInUsdg(bool maximise) external view returns (uint256);
function lastAddedAt(address _account) external returns (uint256);
function addLiquidity(address _token, uint256 _amount, uint256 _minUsdg, uint256 _minGlp) external returns (uint256);
function addLiquidityForAccount(address _fundingAccount, address _account, address _token, uint256 _amount, uint256 _minUsdg, uint256 _minGlp) external returns (uint256);
function removeLiquidity(address _tokenOut, uint256 _glpAmount, uint256 _minOut, address _receiver) external returns (uint256);
function removeLiquidityForAccount(address _account, address _tokenOut, uint256 _glpAmount, uint256 _minOut, address _receiver) external returns (uint256);
function setShortsTrackerAveragePriceWeight(uint256 _shortsTrackerAveragePriceWeight) external;
function setCooldownDuration(uint256 _cooldownDuration) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IMintable {
function isMinter(address _account) external returns (bool);
function setMinter(address _minter, bool _isActive) external;
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewardRouterV2 {
function feeGlpTracker() external view returns (address);
function stakedGlpTracker() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IRewardTracker {
function depositBalances(address _account, address _depositToken) external view returns (uint256);
function stakedAmounts(address _account) external view returns (uint256);
function updateRewards() external;
function stake(address _depositToken, uint256 _amount) external;
function stakeForAccount(address _fundingAccount, address _account, address _depositToken, uint256 _amount) external;
function unstake(address _depositToken, uint256 _amount) external;
function unstakeForAccount(address _account, address _depositToken, uint256 _amount, address _receiver) external;
function tokensPerInterval() external view returns (uint256);
function claim(address _receiver) external returns (uint256);
function claimForAccount(address _account, address _receiver) external returns (uint256);
function claimable(address _account) external view returns (uint256);
function averageStakedAmounts(address _account) external view returns (uint256);
function cumulativeRewards(address _account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IVaultUtils.sol";
interface IVault {
function isInitialized() external view returns (bool);
function isSwapEnabled() external view returns (bool);
function isLeverageEnabled() external view returns (bool);
function setVaultUtils(IVaultUtils _vaultUtils) external;
function setError(uint256 _errorCode, string calldata _error) external;
function router() external view returns (address);
function usdg() external view returns (address);
function gov() external view returns (address);
function whitelistedTokenCount() external view returns (uint256);
function maxLeverage() external view returns (uint256);
function minProfitTime() external view returns (uint256);
function hasDynamicFees() external view returns (bool);
function fundingInterval() external view returns (uint256);
function totalTokenWeights() external view returns (uint256);
function getTargetUsdgAmount(address _token) external view returns (uint256);
function inManagerMode() external view returns (bool);
function inPrivateLiquidationMode() external view returns (bool);
function maxGasPrice() external view returns (uint256);
function approvedRouters(address _account, address _router) external view returns (bool);
function isLiquidator(address _account) external view returns (bool);
function isManager(address _account) external view returns (bool);
function minProfitBasisPoints(address _token) external view returns (uint256);
function tokenBalances(address _token) external view returns (uint256);
function lastFundingTimes(address _token) external view returns (uint256);
function setMaxLeverage(uint256 _maxLeverage) external;
function setInManagerMode(bool _inManagerMode) external;
function setManager(address _manager, bool _isManager) external;
function setIsSwapEnabled(bool _isSwapEnabled) external;
function setIsLeverageEnabled(bool _isLeverageEnabled) external;
function setMaxGasPrice(uint256 _maxGasPrice) external;
function setUsdgAmount(address _token, uint256 _amount) external;
function setBufferAmount(address _token, uint256 _amount) external;
function setMaxGlobalShortSize(address _token, uint256 _amount) external;
function setInPrivateLiquidationMode(bool _inPrivateLiquidationMode) external;
function setLiquidator(address _liquidator, bool _isActive) external;
function setFundingRate(uint256 _fundingInterval, uint256 _fundingRateFactor, uint256 _stableFundingRateFactor) external;
function setFees(
uint256 _taxBasisPoints,
uint256 _stableTaxBasisPoints,
uint256 _mintBurnFeeBasisPoints,
uint256 _swapFeeBasisPoints,
uint256 _stableSwapFeeBasisPoints,
uint256 _marginFeeBasisPoints,
uint256 _liquidationFeeUsd,
uint256 _minProfitTime,
bool _hasDynamicFees
) external;
function setTokenConfig(
address _token,
uint256 _tokenDecimals,
uint256 _redemptionBps,
uint256 _minProfitBps,
uint256 _maxUsdgAmount,
bool _isStable,
bool _isShortable
) external;
function setPriceFeed(address _priceFeed) external;
function withdrawFees(address _token, address _receiver) external returns (uint256);
function directPoolDeposit(address _token) external;
function buyUSDG(address _token, address _receiver) external returns (uint256);
function sellUSDG(address _token, address _receiver) external returns (uint256);
function swap(address _tokenIn, address _tokenOut, address _receiver) external returns (uint256);
function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external;
function decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256);
function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
function liquidatePosition(address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver) external;
function tokenToUsdMin(address _token, uint256 _tokenAmount) external view returns (uint256);
function priceFeed() external view returns (address);
function fundingRateFactor() external view returns (uint256);
function stableFundingRateFactor() external view returns (uint256);
function cumulativeFundingRates(address _token) external view returns (uint256);
function getNextFundingRate(address _token) external view returns (uint256);
function getFeeBasisPoints(address _token, uint256 _usdgDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
function liquidationFeeUsd() external view returns (uint256);
function taxBasisPoints() external view returns (uint256);
function stableTaxBasisPoints() external view returns (uint256);
function mintBurnFeeBasisPoints() external view returns (uint256);
function swapFeeBasisPoints() external view returns (uint256);
function stableSwapFeeBasisPoints() external view returns (uint256);
function marginFeeBasisPoints() external view returns (uint256);
function allWhitelistedTokensLength() external view returns (uint256);
function allWhitelistedTokens(uint256) external view returns (address);
function whitelistedTokens(address _token) external view returns (bool);
function stableTokens(address _token) external view returns (bool);
function shortableTokens(address _token) external view returns (bool);
function feeReserves(address _token) external view returns (uint256);
function globalShortSizes(address _token) external view returns (uint256);
function globalShortAveragePrices(address _token) external view returns (uint256);
function maxGlobalShortSizes(address _token) external view returns (uint256);
function tokenDecimals(address _token) external view returns (uint256);
function tokenWeights(address _token) external view returns (uint256);
function guaranteedUsd(address _token) external view returns (uint256);
function poolAmounts(address _token) external view returns (uint256);
function bufferAmounts(address _token) external view returns (uint256);
function reservedAmounts(address _token) external view returns (uint256);
function usdgAmounts(address _token) external view returns (uint256);
function maxUsdgAmounts(address _token) external view returns (uint256);
function getRedemptionAmount(address _token, uint256 _usdgAmount) external view returns (uint256);
function getMaxPrice(address _token) external view returns (uint256);
function getMinPrice(address _token) external view returns (uint256);
function getDelta(address _indexToken, uint256 _size, uint256 _averagePrice, bool _isLong, uint256 _lastIncreasedTime) external view returns (bool, uint256);
function getPosition(address _account, address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, bool, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IVaultUtils {
function updateCumulativeFundingRate(address _collateralToken, address _indexToken) external returns (bool);
function validateIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external view;
function validateDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external view;
function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) external view returns (uint256, uint256);
function getEntryFundingRate(address _collateralToken, address _indexToken, bool _isLong) external view returns (uint256);
function getPositionFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta) external view returns (uint256);
function getFundingFee(address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _size, uint256 _entryFundingRate) external view returns (uint256);
function getBuyUsdgFeeBasisPoints(address _token, uint256 _usdgAmount) external view returns (uint256);
function getSellUsdgFeeBasisPoints(address _token, uint256 _usdgAmount) external view returns (uint256);
function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdgAmount) external view returns (uint256);
function getFeeBasisPoints(address _token, uint256 _usdgDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IVester {
function rewardTracker() external view returns (address);
function claimForAccount(address _account, address _receiver) external returns (uint256);
function claimable(address _account) external view returns (uint256);
function cumulativeClaimAmounts(address _account) external view returns (uint256);
function claimedAmounts(address _account) external view returns (uint256);
function pairAmounts(address _account) external view returns (uint256);
function getVestedAmount(address _account) external view returns (uint256);
function transferredAverageStakedAmounts(address _account) external view returns (uint256);
function transferredCumulativeRewards(address _account) external view returns (uint256);
function cumulativeRewardDeductions(address _account) external view returns (uint256);
function bonusRewards(address _account) external view returns (uint256);
function transferStakeValues(address _sender, address _receiver) external;
function setTransferredAverageStakedAmounts(address _account, uint256 _amount) external;
function setTransferredCumulativeRewards(address _account, uint256 _amount) external;
function setCumulativeRewardDeductions(address _account, uint256 _amount) external;
function setBonusRewards(address _account, uint256 _amount) external;
function getMaxVestableAmount(address _account) external view returns (uint256);
function getCombinedAverageStakedAmount(address _account) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../libraries/math/SafeMath.sol";
import "../libraries/token/IERC20.sol";
import "../libraries/token/SafeERC20.sol";
import "../libraries/utils/ReentrancyGuard.sol";
import "../libraries/utils/Address.sol";
import "./interfaces/IExternalHandler.sol";
import "./interfaces/IRewardTracker.sol";
import "./interfaces/IRewardRouterV2.sol";
import "./interfaces/IVester.sol";
import "../tokens/interfaces/IMintable.sol";
import "../tokens/interfaces/IWETH.sol";
import "../core/interfaces/IGlpManager.sol";
import "../access/Governable.sol";
contract RewardRouterV2 is IRewardRouterV2, ReentrancyGuard, Governable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address payable;
enum VotingPowerType {
None,
BaseStakedAmount,
BaseAndBonusStakedAmount
}
struct InitializeParams {
address weth;
address gmx;
address esGmx;
address bnGmx;
address glp;
address stakedGmxTracker;
address bonusGmxTracker;
address extendedGmxTracker;
address feeGmxTracker;
address feeGlpTracker;
address stakedGlpTracker;
address glpManager;
address gmxVester;
address glpVester;
address externalHandler;
address govToken;
}
uint256 public constant BASIS_POINTS_DIVISOR = 10000;
bool public isInitialized;
address public weth;
address public gmx;
address public esGmx;
address public bnGmx;
address public glp; // GMX Liquidity Provider token
address public stakedGmxTracker;
address public bonusGmxTracker;
address public extendedGmxTracker;
address public feeGmxTracker;
address public override stakedGlpTracker;
address public override feeGlpTracker;
address public glpManager;
address public gmxVester;
address public glpVester;
address public externalHandler;
uint256 public maxBoostBasisPoints;
bool public inStrictTransferMode;
address public govToken;
VotingPowerType public votingPowerType;
bool public inRestakingMode;
mapping (address => address) public pendingReceivers;
event StakeGmx(address account, address token, uint256 amount);
event UnstakeGmx(address account, address token, uint256 amount);
event StakeGlp(address account, uint256 amount);
event UnstakeGlp(address account, uint256 amount);
receive() external payable {
require(msg.sender == weth, "Router: invalid sender");
}
function initialize(InitializeParams memory _initializeParams) external onlyGov {
require(!isInitialized, "already initialized");
isInitialized = true;
weth = _initializeParams.weth;
gmx = _initializeParams.gmx;
esGmx = _initializeParams.esGmx;
bnGmx = _initializeParams.bnGmx;
glp = _initializeParams.glp;
stakedGmxTracker = _initializeParams.stakedGmxTracker;
bonusGmxTracker = _initializeParams.bonusGmxTracker;
extendedGmxTracker = _initializeParams.extendedGmxTracker;
feeGmxTracker = _initializeParams.feeGmxTracker;
feeGlpTracker = _initializeParams.feeGlpTracker;
stakedGlpTracker = _initializeParams.stakedGlpTracker;
glpManager = _initializeParams.glpManager;
gmxVester = _initializeParams.gmxVester;
glpVester = _initializeParams.glpVester;
externalHandler = _initializeParams.externalHandler;
govToken = _initializeParams.govToken;
}
function setGovToken(address _govToken) external onlyGov {
govToken = _govToken;
}
function setInStrictTransferMode(bool _inStrictTransferMode) external onlyGov {
inStrictTransferMode = _inStrictTransferMode;
}
function setMaxBoostBasisPoints(uint256 _maxBoostBasisPoints) external onlyGov {
maxBoostBasisPoints = _maxBoostBasisPoints;
}
function setVotingPowerType(VotingPowerType _votingPowerType) external onlyGov {
votingPowerType = _votingPowerType;
}
function setInRestakingMode(bool _inRestakingMode) external onlyGov {
inRestakingMode = _inRestakingMode;
}
// to help users who accidentally send their tokens to this contract
function withdrawToken(address _token, address _account, uint256 _amount) external onlyGov {
IERC20(_token).safeTransfer(_account, _amount);
}
function batchStakeGmxForAccounts(address[] memory _accounts, uint256[] memory _amounts) external nonReentrant onlyGov {
address _gmx = gmx;
for (uint256 i = 0; i < _accounts.length; i++) {
_stakeGmx(msg.sender, _accounts[i], _gmx, _amounts[i]);
}
}
function batchCompoundForAccounts(address[] memory _accounts) external nonReentrant onlyGov {
for (uint256 i = 0; i < _accounts.length; i++) {
_compound(_accounts[i]);
}
}
function batchRestakeForAccounts(address[] memory _accounts) external nonReentrant onlyGov {
for (uint256 i = 0; i < _accounts.length; i++) {
_restakeForAccount(_accounts[i]);
}
}
function multicall(bytes[] memory data) external returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
require(success, "call failed");
results[i] = result;
}
return results;
}
function makeExternalCalls(
address[] memory externalCallTargets,
bytes[] memory externalCallDataList,
address[] memory refundTokens,
address[] memory refundReceivers
) external nonReentrant {
IExternalHandler(externalHandler).makeExternalCalls(
externalCallTargets,
externalCallDataList,
refundTokens,
refundReceivers
);
}
function stakeGmx(uint256 _amount) external nonReentrant {
_stakeGmx(msg.sender, msg.sender, gmx, _amount);
}
function stakeEsGmx(uint256 _amount) external nonReentrant {
_stakeGmx(msg.sender, msg.sender, esGmx, _amount);
}
function unstakeGmx(uint256 _amount) external nonReentrant {
_restakeForAccount(msg.sender);
_unstakeGmx(msg.sender, gmx, _amount, true);
}
function unstakeEsGmx(uint256 _amount) external nonReentrant {
_restakeForAccount(msg.sender);
_unstakeGmx(msg.sender, esGmx, _amount, true);
}
function mintAndStakeGlp(address _token, uint256 _amount, uint256 _minUsdg, uint256 _minGlp) external nonReentrant returns (uint256) {
_validateAmount(_amount);
uint256 glpAmount = _mintAndStakeGlp(msg.sender, _token, _amount, _minUsdg, _minGlp);
emit StakeGlp(msg.sender, glpAmount);
return glpAmount;
}
function mintAndStakeGlpETH(uint256 _minUsdg, uint256 _minGlp) external payable nonReentrant returns (uint256) {
require(msg.value > 0, "invalid msg.value");
IWETH(weth).deposit{value: msg.value}();
IERC20(weth).approve(glpManager, msg.value);
uint256 glpAmount = _mintAndStakeGlp(address(this), weth, msg.value, _minUsdg, _minGlp);
emit StakeGlp(msg.sender, glpAmount);
return glpAmount;
}
function unstakeAndRedeemGlp(address _tokenOut, uint256 _glpAmount, uint256 _minOut, address _receiver) external nonReentrant returns (uint256) {
uint256 amountOut = _unstakeAndRedeemGlp(_tokenOut, _glpAmount, _minOut, _receiver);
emit UnstakeGlp(msg.sender, _glpAmount);
return amountOut;
}
function unstakeAndRedeemGlpETH(uint256 _glpAmount, uint256 _minOut, address payable _receiver) external nonReentrant returns (uint256) {
uint256 amountOut = _unstakeAndRedeemGlp(weth, _glpAmount, _minOut, address(this));
IWETH(weth).withdraw(amountOut);
_receiver.sendValue(amountOut);
emit UnstakeGlp(msg.sender, _glpAmount);
return amountOut;
}
function claim() external nonReentrant {
_claim(stakedGmxTracker, stakedGlpTracker, msg.sender, msg.sender);
_claimGmxFees(msg.sender, msg.sender);
_claim(feeGmxTracker, feeGlpTracker, msg.sender, msg.sender);
}
function claimEsGmx() external nonReentrant {
_claim(stakedGmxTracker, stakedGlpTracker, msg.sender, msg.sender);
}
function claimFees() external nonReentrant {
_claimGmxFees(msg.sender, msg.sender);
_claim(feeGmxTracker, feeGlpTracker, msg.sender, msg.sender);
}
function compound() external nonReentrant {
_compound(msg.sender);
}
function handleRewards(
bool _shouldClaimGmx,
bool _shouldStakeGmx,
bool _shouldClaimEsGmx,
bool _shouldStakeEsGmx,
bool _shouldStakeMultiplierPoints,
bool _shouldClaimWeth,
bool _shouldConvertWethToEth
) external nonReentrant {
address account = msg.sender;
uint256 gmxAmount = 0;
if (_shouldClaimGmx) {
uint256 gmxAmount0 = _claimVestedGmx(account, account);
uint256 gmxAmount1 = _claimGmxFees(account, account);
gmxAmount = gmxAmount0.add(gmxAmount1);
}
if (_shouldStakeGmx && gmxAmount > 0) {
_stakeGmx(account, account, gmx, gmxAmount);
}
uint256 esGmxAmount = 0;
if (_shouldClaimEsGmx) {
esGmxAmount = _claim(stakedGmxTracker, stakedGlpTracker, account, account);
}
if (_shouldStakeEsGmx && esGmxAmount > 0) {
_stakeGmx(account, account, esGmx, esGmxAmount);
}
if (_shouldStakeMultiplierPoints) {
_restakeForAccount(account);
_stakeBnGmx(account);
}
if (_shouldClaimWeth) {
if (_shouldConvertWethToEth) {
uint256 wethAmount = _claim(feeGmxTracker, feeGlpTracker, account, address(this));
_convertWethToEth(wethAmount);
} else {
_claim(feeGmxTracker, feeGlpTracker, account, account);
}
}
_syncVotingPower(account);
}
function handleRewardsV2(
address _gmxReceiver,
bool _shouldClaimGmx,
bool _shouldStakeGmx,
bool _shouldClaimEsGmx,
bool _shouldStakeEsGmx,
bool _shouldStakeMultiplierPoints,
bool _shouldClaimWeth,
bool _shouldConvertWethToEth
) external nonReentrant {
address account = msg.sender;
uint256 gmxAmount = 0;
if (_shouldClaimGmx) {
uint256 gmxAmount0 = _claimVestedGmx(account, _gmxReceiver);
uint256 gmxAmount1 = _claimGmxFees(account, _gmxReceiver);
gmxAmount = gmxAmount0.add(gmxAmount1);
}
if (_shouldStakeGmx && gmxAmount > 0) {
require(_gmxReceiver == account, "cannot stake GMX if _gmxReceiver != account");
_stakeGmx(account, account, gmx, gmxAmount);
}
uint256 esGmxAmount = 0;
if (_shouldClaimEsGmx) {
esGmxAmount = _claim(stakedGmxTracker, stakedGlpTracker, account, account);
}
if (_shouldStakeEsGmx && esGmxAmount > 0) {
_stakeGmx(account, account, esGmx, esGmxAmount);
}
if (_shouldStakeMultiplierPoints) {
_restakeForAccount(account);
_stakeBnGmx(account);
}
if (_shouldClaimWeth) {
if (_shouldConvertWethToEth) {
uint256 wethAmount = _claim(feeGmxTracker, feeGlpTracker, account, address(this));
_convertWethToEth(wethAmount);
} else {
_claim(feeGmxTracker, feeGlpTracker, account, account);
}
}
_syncVotingPower(account);
}
// the _validateReceiver function checks that the averageStakedAmounts and cumulativeRewards
// values of an account are zero, this is to help ensure that vesting calculations can be
// done correctly
// averageStakedAmounts and cumulativeRewards are updated if the claimable reward for an account
// is more than zero
// it is possible for multiple transfers to be sent into a single account, using signalTransfer and
// acceptTransfer, if those values have not been updated yet
// for GLP transfers it is also possible to transfer GLP into an account using the StakedGlp contract
function signalTransfer(address _receiver) external nonReentrant {
_validateNotVesting(msg.sender);
_validateReceiver(_receiver);
if (inStrictTransferMode) {
uint256 balance = IRewardTracker(feeGmxTracker).stakedAmounts(msg.sender);
uint256 allowance = IERC20(feeGmxTracker).allowance(msg.sender, _receiver);
require(allowance >= balance, "insufficient allowance");
}
pendingReceivers[msg.sender] = _receiver;
}
function acceptTransfer(address _sender) external nonReentrant {
_validateNotVesting(_sender);
address receiver = msg.sender;
require(pendingReceivers[_sender] == receiver, "transfer not signalled");
delete pendingReceivers[_sender];
_validateReceiver(receiver);
_compound(_sender);
uint256 stakedGmx = IRewardTracker(stakedGmxTracker).depositBalances(_sender, gmx);
if (stakedGmx > 0) {
_unstakeGmx(_sender, gmx, stakedGmx, false);
_stakeGmx(_sender, receiver, gmx, stakedGmx);
}
uint256 stakedEsGmx = IRewardTracker(stakedGmxTracker).depositBalances(_sender, esGmx);
if (stakedEsGmx > 0) {
_unstakeGmx(_sender, esGmx, stakedEsGmx, false);
_stakeGmx(_sender, receiver, esGmx, stakedEsGmx);
}
uint256 stakedBnGmx = IRewardTracker(extendedGmxTracker).depositBalances(_sender, bnGmx);
_acceptTransferRestake(feeGmxTracker, extendedGmxTracker, _sender, receiver, bnGmx, stakedBnGmx);
uint256 esGmxBalance = IERC20(esGmx).balanceOf(_sender);
if (esGmxBalance > 0) {
IERC20(esGmx).transferFrom(_sender, receiver, esGmxBalance);
}
uint256 bnGmxBalance = IERC20(bnGmx).balanceOf(_sender);
if (bnGmxBalance > 0) {
_burnToken(bnGmx, _sender, bnGmxBalance);
_mintToken(bnGmx, receiver, bnGmxBalance);
}
uint256 glpAmount = IRewardTracker(feeGlpTracker).depositBalances(_sender, glp);
_acceptTransferRestake(stakedGlpTracker, feeGlpTracker, _sender, receiver, glp, glpAmount);
IVester(gmxVester).transferStakeValues(_sender, receiver);
IVester(glpVester).transferStakeValues(_sender, receiver);
_syncVotingPower(_sender);
_syncVotingPower(receiver);
}
function _claim(address _rewardTracker0, address _rewardTracker1, address _account, address _receiver) private returns (uint256) {
uint256 amount0 = IRewardTracker(_rewardTracker0).claimForAccount(_account, _receiver);
uint256 amount1 = IRewardTracker(_rewardTracker1).claimForAccount(_account, _receiver);
uint256 amount = amount0.add(amount1);
return(amount);
}
function _claimGmxFees(address _account, address _receiver) private returns (uint256) {
uint256 gmxAmount = IRewardTracker(extendedGmxTracker).claimForAccount(_account, _receiver);
return(gmxAmount);
}
function _claimVestedGmx(address _account, address _receiver) private returns (uint256) {
uint256 gmxAmount0 = IVester(gmxVester).claimForAccount(_account, _receiver);
uint256 gmxAmount1 = IVester(glpVester).claimForAccount(_account, _receiver);
uint256 gmxAmount = gmxAmount0.add(gmxAmount1);
return (gmxAmount);
}
function _convertWethToEth(uint256 _amount) private {
IWETH(weth).withdraw(_amount);
payable(msg.sender).sendValue(_amount);
}
function _compound(address _account) private {
uint256 gmxAmount = _claimGmxFees(_account, _account);
if (gmxAmount > 0) {
_stakeGmx(_account, _account, gmx, gmxAmount);
}
uint256 esGmxAmount = _claim(stakedGmxTracker, stakedGlpTracker, _account, _account);
if (esGmxAmount > 0) {
_stakeGmx(_account, _account, esGmx, esGmxAmount);
}
_restakeForAccount(_account);
_stakeBnGmx(_account);
_syncVotingPower(_account);
}
function _stakeGmx(address _fundingAccount, address _account, address _token, uint256 _amount) private {
_validateAmount(_amount);
IRewardTracker(stakedGmxTracker).stakeForAccount(_fundingAccount, _account, _token, _amount);
IRewardTracker(bonusGmxTracker).stakeForAccount(_account, _account, stakedGmxTracker, _amount);
IRewardTracker(extendedGmxTracker).stakeForAccount(_account, _account, bonusGmxTracker, _amount);
IRewardTracker(feeGmxTracker).stakeForAccount(_account, _account, extendedGmxTracker, _amount);
_syncVotingPower(_account);
emit StakeGmx(_account, _token, _amount);
}
// note that _syncVotingPower is not called here, in functions which
// call _stakeBnGmx it should be ensured that _syncVotingPower is called
// after
function _stakeBnGmx(address _account) private {
IRewardTracker(bonusGmxTracker).claimForAccount(_account, _account);
// get the bnGmx balance of the user, this would be the amount of
// bnGmx that has not been staked
uint256 bnGmxAmount = IERC20(bnGmx).balanceOf(_account);
if (bnGmxAmount == 0) { return; }
// get the baseStakedAmount which would be the sum of staked gmx and staked esGmx tokens
uint256 baseStakedAmount = IRewardTracker(stakedGmxTracker).stakedAmounts(_account);
uint256 maxAllowedBnGmxAmount = baseStakedAmount.mul(maxBoostBasisPoints).div(BASIS_POINTS_DIVISOR);
uint256 currentBnGmxAmount = IRewardTracker(extendedGmxTracker).depositBalances(_account, bnGmx);
if (currentBnGmxAmount == maxAllowedBnGmxAmount) { return; }
// if the currentBnGmxAmount is more than the maxAllowedBnGmxAmount
// unstake the excess tokens
if (currentBnGmxAmount > maxAllowedBnGmxAmount) {
uint256 amountToUnstake = currentBnGmxAmount.sub(maxAllowedBnGmxAmount);
IRewardTracker(feeGmxTracker).unstakeForAccount(_account, extendedGmxTracker, amountToUnstake, _account);
IRewardTracker(extendedGmxTracker).unstakeForAccount(_account, bnGmx, amountToUnstake, _account);
return;
}
uint256 maxStakeableBnGmxAmount = maxAllowedBnGmxAmount.sub(currentBnGmxAmount);
if (bnGmxAmount > maxStakeableBnGmxAmount) {
bnGmxAmount = maxStakeableBnGmxAmount;
}
IRewardTracker(extendedGmxTracker).stakeForAccount(_account, _account, bnGmx, bnGmxAmount);
IRewardTracker(feeGmxTracker).stakeForAccount(_account, _account, extendedGmxTracker, bnGmxAmount);
}
function _unstakeGmx(address _account, address _token, uint256 _amount, bool _shouldReduceBnGmx) private {
_validateAmount(_amount);
uint256 balance = IRewardTracker(stakedGmxTracker).stakedAmounts(_account);
IRewardTracker(feeGmxTracker).unstakeForAccount(_account, extendedGmxTracker, _amount, _account);
IRewardTracker(extendedGmxTracker).unstakeForAccount(_account, bonusGmxTracker, _amount, _account);
IRewardTracker(bonusGmxTracker).unstakeForAccount(_account, stakedGmxTracker, _amount, _account);
IRewardTracker(stakedGmxTracker).unstakeForAccount(_account, _token, _amount, _account);
if (_shouldReduceBnGmx) {
IRewardTracker(bonusGmxTracker).claimForAccount(_account, _account);
// unstake and burn staked bnGmx tokens
uint256 stakedBnGmx = IRewardTracker(extendedGmxTracker).depositBalances(_account, bnGmx);
if (stakedBnGmx > 0) {
uint256 reductionAmount = stakedBnGmx.mul(_amount).div(balance);
IRewardTracker(feeGmxTracker).unstakeForAccount(_account, extendedGmxTracker, reductionAmount, _account);
IRewardTracker(extendedGmxTracker).unstakeForAccount(_account, bnGmx, reductionAmount, _account);
_burnToken(bnGmx, _account, reductionAmount);
}
// burn bnGmx tokens from user's balance
uint256 bnGmxBalance = IERC20(bnGmx).balanceOf(_account);
if (bnGmxBalance > 0) {
uint256 amountToBurn = bnGmxBalance.mul(_amount).div(balance);
_burnToken(bnGmx, _account, amountToBurn);
}
}
_syncVotingPower(_account);
emit UnstakeGmx(_account, _token, _amount);
}
function _syncVotingPower(address _account) private {
if (votingPowerType == VotingPowerType.None) {
return;
}
if (votingPowerType == VotingPowerType.BaseStakedAmount) {
uint256 baseStakedAmount = IRewardTracker(stakedGmxTracker).stakedAmounts(_account);
_syncVotingPower(_account, baseStakedAmount);
return;
}
if (votingPowerType == VotingPowerType.BaseAndBonusStakedAmount) {
uint256 stakedAmount = IRewardTracker(feeGmxTracker).stakedAmounts(_account);
_syncVotingPower(_account, stakedAmount);
return;
}
revert("unsupported votingPowerType");
}
function _syncVotingPower(address _account, uint256 _amount) private {
uint256 currentVotingPower = IERC20(govToken).balanceOf(_account);
if (currentVotingPower == _amount) { return; }
if (currentVotingPower > _amount) {
uint256 amountToBurn = currentVotingPower.sub(_amount);
_burnToken(govToken, _account, amountToBurn);
return;
}
uint256 amountToMint = _amount.sub(currentVotingPower);
_mintToken(govToken, _account, amountToMint);
}
function _mintAndStakeGlp(address _address, address _token, uint256 _amount, uint256 _minUsdg, uint256 _minGlp) private returns (uint256) {
address account = msg.sender;
uint256 glpAmount = IGlpManager(glpManager).addLiquidityForAccount(_address, account, _token, _amount, _minUsdg, _minGlp);
IRewardTracker(feeGlpTracker).stakeForAccount(account, account, glp, glpAmount);
IRewardTracker(stakedGlpTracker).stakeForAccount(account, account, feeGlpTracker, glpAmount);
return glpAmount;
}
function _unstakeAndRedeemGlp(address _tokenOut, uint256 _glpAmount, uint256 _minOut, address _receiver) private returns (uint256) {
require(_glpAmount > 0, "invalid _glpAmount");
address account = msg.sender;
IRewardTracker(stakedGlpTracker).unstakeForAccount(account, feeGlpTracker, _glpAmount, account);
IRewardTracker(feeGlpTracker).unstakeForAccount(account, glp, _glpAmount, account);
uint256 amountOut = IGlpManager(glpManager).removeLiquidityForAccount(account, _tokenOut, _glpAmount, _minOut, _receiver);
return amountOut;
}
function _restakeForAccount(address _account) private {
if (!inRestakingMode) { return; }
uint256 bonusGmxTrackerBalance = IRewardTracker(feeGmxTracker).depositBalances(_account, bonusGmxTracker);
if (bonusGmxTrackerBalance > 0) {
uint256 reservedForVesting = IVester(gmxVester).pairAmounts(_account);
if (reservedForVesting > 0) {
IERC20(feeGmxTracker).safeTransferFrom(gmxVester, _account, reservedForVesting);
_restakeBonusGmxTracker(_account, bonusGmxTrackerBalance);
_restakeBnGmx(_account);
IERC20(feeGmxTracker).safeTransferFrom(_account, gmxVester, reservedForVesting);
}
else {
_restakeBonusGmxTracker(_account, bonusGmxTrackerBalance);
_restakeBnGmx(_account);
}
}
}
function _restakeBonusGmxTracker(address _account, uint256 _bonusGmxTrackerBalance) private {
IRewardTracker(feeGmxTracker).unstakeForAccount(_account, bonusGmxTracker, _bonusGmxTrackerBalance, _account);
IRewardTracker(extendedGmxTracker).stakeForAccount(_account, _account, bonusGmxTracker, _bonusGmxTrackerBalance);
IRewardTracker(feeGmxTracker).stakeForAccount(_account, _account, extendedGmxTracker, _bonusGmxTrackerBalance);
}
function _restakeBnGmx(address _account) private {
uint256 stakedBnGmx = IRewardTracker(feeGmxTracker).depositBalances(_account, bnGmx);
if (stakedBnGmx > 0) {
IRewardTracker(feeGmxTracker).unstakeForAccount(_account, bnGmx, stakedBnGmx, _account);
_stakeBnGmx(_account);
_syncVotingPower(_account);
}
}
function _acceptTransferRestake(address _rewardTracker0, address _rewardTracker1, address _sender, address _receiver, address _token, uint256 _amount) private {
if (_amount > 0) {
IRewardTracker(_rewardTracker0).unstakeForAccount(_sender, _rewardTracker1, _amount, _sender);
IRewardTracker(_rewardTracker1).unstakeForAccount(_sender, _token, _amount, _sender);
IRewardTracker(_rewardTracker1).stakeForAccount(_sender, _receiver, _token, _amount);
IRewardTracker(_rewardTracker0).stakeForAccount(_receiver, _receiver, _rewardTracker1, _amount);
}
}
function _mintToken(address _token, address _account, uint256 _amountToMint) private {
IMintable(_token).mint(_account, _amountToMint);
}
function _burnToken(address _token, address _account, uint256 _amountToBurn) private {
IMintable(_token).burn(_account, _amountToBurn);
}
function _validateReceiver(address _receiver) private view {
require(IRewardTracker(stakedGmxTracker).averageStakedAmounts(_receiver) == 0, "stakedGmxTracker.averageStakedAmounts > 0");
require(IRewardTracker(stakedGmxTracker).cumulativeRewards(_receiver) == 0, "stakedGmxTracker.cumulativeRewards > 0");
require(IRewardTracker(bonusGmxTracker).averageStakedAmounts(_receiver) == 0, "bonusGmxTracker.averageStakedAmounts > 0");
require(IRewardTracker(bonusGmxTracker).cumulativeRewards(_receiver) == 0, "bonusGmxTracker.cumulativeRewards > 0");
require(IRewardTracker(extendedGmxTracker).averageStakedAmounts(_receiver) == 0, "extendedGmxTracker.averageStakedAmounts > 0");
require(IRewardTracker(extendedGmxTracker).cumulativeRewards(_receiver) == 0, "extendedGmxTracker.cumulativeRewards > 0");
require(IRewardTracker(feeGmxTracker).averageStakedAmounts(_receiver) == 0, "feeGmxTracker.averageStakedAmounts > 0");
require(IRewardTracker(feeGmxTracker).cumulativeRewards(_receiver) == 0, "feeGmxTracker.cumulativeRewards > 0");
require(IVester(gmxVester).transferredAverageStakedAmounts(_receiver) == 0, "gmxVester.transferredAverageStakedAmounts > 0");
require(IVester(gmxVester).transferredCumulativeRewards(_receiver) == 0, "gmxVester.transferredCumulativeRewards > 0");
require(IRewardTracker(stakedGlpTracker).averageStakedAmounts(_receiver) == 0, "stakedGlpTracker.averageStakedAmounts > 0");
require(IRewardTracker(stakedGlpTracker).cumulativeRewards(_receiver) == 0, "stakedGlpTracker.cumulativeRewards > 0");
require(IRewardTracker(feeGlpTracker).averageStakedAmounts(_receiver) == 0, "feeGlpTracker.averageStakedAmounts > 0");
require(IRewardTracker(feeGlpTracker).cumulativeRewards(_receiver) == 0, "feeGlpTracker.cumulativeRewards > 0");
require(IVester(glpVester).transferredAverageStakedAmounts(_receiver) == 0, "gmxVester.transferredAverageStakedAmounts > 0");
require(IVester(glpVester).transferredCumulativeRewards(_receiver) == 0, "gmxVester.transferredCumulativeRewards > 0");
require(IERC20(gmxVester).balanceOf(_receiver) == 0, "gmxVester.balance > 0");
require(IERC20(glpVester).balanceOf(_receiver) == 0, "glpVester.balance > 0");
}
function _validateNotVesting(address _sender) private view {
require(IERC20(gmxVester).balanceOf(_sender) == 0 && IERC20(glpVester).balanceOf(_sender) == 0, "sender has vested tokens");
}
function _validateAmount(uint256 _amount) private pure {
require(_amount > 0, "invalid _amount");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC20.sol";
import "../math/SafeMath.sol";
import "../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
{
"compilationTarget": {
"contracts/staking/RewardRouterV2.sol": "RewardRouterV2"
},
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 10
},
"remappings": []
}
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"StakeGlp","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"StakeGmx","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"UnstakeGlp","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"UnstakeGmx","type":"event"},{"inputs":[],"name":"BASIS_POINTS_DIVISOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_sender","type":"address"}],"name":"acceptTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_accounts","type":"address[]"}],"name":"batchCompoundForAccounts","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_accounts","type":"address[]"}],"name":"batchRestakeForAccounts","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_accounts","type":"address[]"},{"internalType":"uint256[]","name":"_amounts","type":"uint256[]"}],"name":"batchStakeGmxForAccounts","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"bnGmx","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bonusGmxTracker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimEsGmx","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"compound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"esGmx","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"extendedGmxTracker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"externalHandler","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeGlpTracker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeGmxTracker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"glp","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"glpManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"glpVester","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gmx","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gmxVester","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gov","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"govToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_shouldClaimGmx","type":"bool"},{"internalType":"bool","name":"_shouldStakeGmx","type":"bool"},{"internalType":"bool","name":"_shouldClaimEsGmx","type":"bool"},{"internalType":"bool","name":"_shouldStakeEsGmx","type":"bool"},{"internalType":"bool","name":"_shouldStakeMultiplierPoints","type":"bool"},{"internalType":"bool","name":"_shouldClaimWeth","type":"bool"},{"internalType":"bool","name":"_shouldConvertWethToEth","type":"bool"}],"name":"handleRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_gmxReceiver","type":"address"},{"internalType":"bool","name":"_shouldClaimGmx","type":"bool"},{"internalType":"bool","name":"_shouldStakeGmx","type":"bool"},{"internalType":"bool","name":"_shouldClaimEsGmx","type":"bool"},{"internalType":"bool","name":"_shouldStakeEsGmx","type":"bool"},{"internalType":"bool","name":"_shouldStakeMultiplierPoints","type":"bool"},{"internalType":"bool","name":"_shouldClaimWeth","type":"bool"},{"internalType":"bool","name":"_shouldConvertWethToEth","type":"bool"}],"name":"handleRewardsV2","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"inRestakingMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"inStrictTransferMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"weth","type":"address"},{"internalType":"address","name":"gmx","type":"address"},{"internalType":"address","name":"esGmx","type":"address"},{"internalType":"address","name":"bnGmx","type":"address"},{"internalType":"address","name":"glp","type":"address"},{"internalType":"address","name":"stakedGmxTracker","type":"address"},{"internalType":"address","name":"bonusGmxTracker","type":"address"},{"internalType":"address","name":"extendedGmxTracker","type":"address"},{"internalType":"address","name":"feeGmxTracker","type":"address"},{"internalType":"address","name":"feeGlpTracker","type":"address"},{"internalType":"address","name":"stakedGlpTracker","type":"address"},{"internalType":"address","name":"glpManager","type":"address"},{"internalType":"address","name":"gmxVester","type":"address"},{"internalType":"address","name":"glpVester","type":"address"},{"internalType":"address","name":"externalHandler","type":"address"},{"internalType":"address","name":"govToken","type":"address"}],"internalType":"struct RewardRouterV2.InitializeParams","name":"_initializeParams","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isInitialized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"externalCallTargets","type":"address[]"},{"internalType":"bytes[]","name":"externalCallDataList","type":"bytes[]"},{"internalType":"address[]","name":"refundTokens","type":"address[]"},{"internalType":"address[]","name":"refundReceivers","type":"address[]"}],"name":"makeExternalCalls","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maxBoostBasisPoints","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint256","name":"_minUsdg","type":"uint256"},{"internalType":"uint256","name":"_minGlp","type":"uint256"}],"name":"mintAndStakeGlp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minUsdg","type":"uint256"},{"internalType":"uint256","name":"_minGlp","type":"uint256"}],"name":"mintAndStakeGlpETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"pendingReceivers","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_gov","type":"address"}],"name":"setGov","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_govToken","type":"address"}],"name":"setGovToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_inRestakingMode","type":"bool"}],"name":"setInRestakingMode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_inStrictTransferMode","type":"bool"}],"name":"setInStrictTransferMode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxBoostBasisPoints","type":"uint256"}],"name":"setMaxBoostBasisPoints","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum RewardRouterV2.VotingPowerType","name":"_votingPowerType","type":"uint8"}],"name":"setVotingPowerType","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_receiver","type":"address"}],"name":"signalTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"stakeEsGmx","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"stakeGmx","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakedGlpTracker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stakedGmxTracker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenOut","type":"address"},{"internalType":"uint256","name":"_glpAmount","type":"uint256"},{"internalType":"uint256","name":"_minOut","type":"uint256"},{"internalType":"address","name":"_receiver","type":"address"}],"name":"unstakeAndRedeemGlp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_glpAmount","type":"uint256"},{"internalType":"uint256","name":"_minOut","type":"uint256"},{"internalType":"address payable","name":"_receiver","type":"address"}],"name":"unstakeAndRedeemGlpETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"unstakeEsGmx","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"unstakeGmx","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"votingPowerType","outputs":[{"internalType":"enum RewardRouterV2.VotingPowerType","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"weth","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_account","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdrawToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]