Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
- Contract name:
- PositionManager
- Optimization enabled
- true
- Compiler version
- v0.6.12+commit.27d51765
- Optimization runs
- 15
- Verified at
- 2023-07-04T16:19:27.121811Z
Constructor Arguments
000000000000000000000000096eedffad8678ed8d74fcdcf71c3c28ebae06490000000000000000000000001b1d7b2756e57d7ff45f3a42fafc4f9b419956460000000000000000000000005f3d354e6c6f57bc891a405251bb898af6b4d0ca000000000000000000000000c86c7c0efbd6a49b35e8714c5f59d99de09a225b000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000368ab183ce0b1acef4f8262fa04596dac2d61633
Arg [0] (address) : 0x096eedffad8678ed8d74fcdcf71c3c28ebae0649
Arg [1] (address) : 0x1b1d7b2756e57d7ff45f3a42fafc4f9b41995646
Arg [2] (address) : 0x5f3d354e6c6f57bc891a405251bb898af6b4d0ca
Arg [3] (address) : 0xc86c7c0efbd6a49b35e8714c5f59d99de09a225b
Arg [4] (uint256) : 30
Arg [5] (address) : 0x368ab183ce0b1acef4f8262fa04596dac2d61633
contracts/core/PositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./interfaces/IRouter.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IOrderBook.sol"; import "../peripherals/interfaces/ITimelock.sol"; import "./BasePositionManager.sol"; contract PositionManager is BasePositionManager { address public orderBook; bool public inLegacyMode; bool public shouldValidateIncreaseOrder = true; mapping (address => bool) public isOrderKeeper; mapping (address => bool) public isPartner; mapping (address => bool) public isLiquidator; event SetOrderKeeper(address indexed account, bool isActive); event SetLiquidator(address indexed account, bool isActive); event SetPartner(address account, bool isActive); event SetInLegacyMode(bool inLegacyMode); event SetShouldValidateIncreaseOrder(bool shouldValidateIncreaseOrder); modifier onlyOrderKeeper() { require(isOrderKeeper[msg.sender], "PositionManager: forbidden"); _; } modifier onlyLiquidator() { require(isLiquidator[msg.sender], "PositionManager: forbidden"); _; } modifier onlyPartnersOrLegacyMode() { require(isPartner[msg.sender] || inLegacyMode, "PositionManager: forbidden"); _; } constructor( address _vault, address _router, address _shortsTracker, address _weth, uint256 _depositFee, address _orderBook ) public BasePositionManager(_vault, _router, _shortsTracker, _weth, _depositFee) { orderBook = _orderBook; } function setOrderKeeper(address _account, bool _isActive) external onlyAdmin { isOrderKeeper[_account] = _isActive; emit SetOrderKeeper(_account, _isActive); } function setLiquidator(address _account, bool _isActive) external onlyAdmin { isLiquidator[_account] = _isActive; emit SetLiquidator(_account, _isActive); } function setPartner(address _account, bool _isActive) external onlyAdmin { isPartner[_account] = _isActive; emit SetPartner(_account, _isActive); } function setInLegacyMode(bool _inLegacyMode) external onlyAdmin { inLegacyMode = _inLegacyMode; emit SetInLegacyMode(_inLegacyMode); } function setShouldValidateIncreaseOrder(bool _shouldValidateIncreaseOrder) external onlyAdmin { shouldValidateIncreaseOrder = _shouldValidateIncreaseOrder; emit SetShouldValidateIncreaseOrder(_shouldValidateIncreaseOrder); } function increasePosition( address[] memory _path, address _indexToken, uint256 _amountIn, uint256 _minOut, uint256 _sizeDelta, bool _isLong, uint256 _price ) external nonReentrant onlyPartnersOrLegacyMode { require(_path.length == 1 || _path.length == 2, "PositionManager: invalid _path.length"); if (_amountIn > 0) { if (_path.length == 1) { IRouter(router).pluginTransfer(_path[0], msg.sender, address(this), _amountIn); } else { IRouter(router).pluginTransfer(_path[0], msg.sender, vault, _amountIn); _amountIn = _swap(_path, _minOut, address(this)); } uint256 afterFeeAmount = _collectFees(msg.sender, _path, _amountIn, _indexToken, _isLong, _sizeDelta); IERC20(_path[_path.length - 1]).safeTransfer(vault, afterFeeAmount); } _increasePosition(msg.sender, _path[_path.length - 1], _indexToken, _sizeDelta, _isLong, _price); } function increasePositionETH( address[] memory _path, address _indexToken, uint256 _minOut, uint256 _sizeDelta, bool _isLong, uint256 _price ) external payable nonReentrant onlyPartnersOrLegacyMode { require(_path.length == 1 || _path.length == 2, "PositionManager: invalid _path.length"); require(_path[0] == weth, "PositionManager: invalid _path"); if (msg.value > 0) { _transferInETH(); uint256 _amountIn = msg.value; if (_path.length > 1) { IERC20(weth).safeTransfer(vault, msg.value); _amountIn = _swap(_path, _minOut, address(this)); } uint256 afterFeeAmount = _collectFees(msg.sender, _path, _amountIn, _indexToken, _isLong, _sizeDelta); IERC20(_path[_path.length - 1]).safeTransfer(vault, afterFeeAmount); } _increasePosition(msg.sender, _path[_path.length - 1], _indexToken, _sizeDelta, _isLong, _price); } function decreasePosition( address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price ) external nonReentrant onlyPartnersOrLegacyMode { _decreasePosition(msg.sender, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, _receiver, _price); } function decreasePositionETH( address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address payable _receiver, uint256 _price ) external nonReentrant onlyPartnersOrLegacyMode { require(_collateralToken == weth, "PositionManager: invalid _collateralToken"); uint256 amountOut = _decreasePosition(msg.sender, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, address(this), _price); _transferOutETHWithGasLimitIgnoreFail(amountOut, _receiver); } function decreasePositionAndSwap( address[] memory _path, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price, uint256 _minOut ) external nonReentrant onlyPartnersOrLegacyMode { require(_path.length == 2, "PositionManager: invalid _path.length"); uint256 amount = _decreasePosition(msg.sender, _path[0], _indexToken, _collateralDelta, _sizeDelta, _isLong, address(this), _price); IERC20(_path[0]).safeTransfer(vault, amount); _swap(_path, _minOut, _receiver); } function decreasePositionAndSwapETH( address[] memory _path, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address payable _receiver, uint256 _price, uint256 _minOut ) external nonReentrant onlyPartnersOrLegacyMode { require(_path.length == 2, "PositionManager: invalid _path.length"); require(_path[_path.length - 1] == weth, "PositionManager: invalid _path"); uint256 amount = _decreasePosition(msg.sender, _path[0], _indexToken, _collateralDelta, _sizeDelta, _isLong, address(this), _price); IERC20(_path[0]).safeTransfer(vault, amount); uint256 amountOut = _swap(_path, _minOut, address(this)); _transferOutETHWithGasLimitIgnoreFail(amountOut, _receiver); } function liquidatePosition( address _account, address _collateralToken, address _indexToken, bool _isLong, address _feeReceiver ) external nonReentrant onlyLiquidator { address _vault = vault; address timelock = IVault(_vault).gov(); (uint256 size, , , , , , , ) = IVault(vault).getPosition(_account, _collateralToken, _indexToken, _isLong); uint256 markPrice = _isLong ? IVault(_vault).getMinPrice(_indexToken) : IVault(_vault).getMaxPrice(_indexToken); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, size, markPrice, false); ITimelock(timelock).enableLeverage(_vault); IVault(_vault).liquidatePosition(_account, _collateralToken, _indexToken, _isLong, _feeReceiver); ITimelock(timelock).disableLeverage(_vault); } function executeSwapOrder(address _account, uint256 _orderIndex, address payable _feeReceiver) external onlyOrderKeeper { IOrderBook(orderBook).executeSwapOrder(_account, _orderIndex, _feeReceiver); } function executeIncreaseOrder(address _account, uint256 _orderIndex, address payable _feeReceiver) external onlyOrderKeeper { _validateIncreaseOrder(_account, _orderIndex); address _vault = vault; address timelock = IVault(_vault).gov(); ( /*address purchaseToken*/, /*uint256 purchaseTokenAmount*/, address collateralToken, address indexToken, uint256 sizeDelta, bool isLong, /*uint256 triggerPrice*/, /*bool triggerAboveThreshold*/, /*uint256 executionFee*/ ) = IOrderBook(orderBook).getIncreaseOrder(_account, _orderIndex); uint256 markPrice = isLong ? IVault(_vault).getMaxPrice(indexToken) : IVault(_vault).getMinPrice(indexToken); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, collateralToken, indexToken, isLong, sizeDelta, markPrice, true); ITimelock(timelock).enableLeverage(_vault); IOrderBook(orderBook).executeIncreaseOrder(_account, _orderIndex, _feeReceiver); ITimelock(timelock).disableLeverage(_vault); _emitIncreasePositionReferral(_account, sizeDelta); } function executeDecreaseOrder(address _account, uint256 _orderIndex, address payable _feeReceiver) external onlyOrderKeeper { address _vault = vault; address timelock = IVault(_vault).gov(); ( address collateralToken, /*uint256 collateralDelta*/, address indexToken, uint256 sizeDelta, bool isLong, /*uint256 triggerPrice*/, /*bool triggerAboveThreshold*/, /*uint256 executionFee*/ ) = IOrderBook(orderBook).getDecreaseOrder(_account, _orderIndex); uint256 markPrice = isLong ? IVault(_vault).getMinPrice(indexToken) : IVault(_vault).getMaxPrice(indexToken); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, collateralToken, indexToken, isLong, sizeDelta, markPrice, false); ITimelock(timelock).enableLeverage(_vault); IOrderBook(orderBook).executeDecreaseOrder(_account, _orderIndex, _feeReceiver); ITimelock(timelock).disableLeverage(_vault); _emitDecreasePositionReferral(_account, sizeDelta); } function _validateIncreaseOrder(address _account, uint256 _orderIndex) internal view { ( address _purchaseToken, uint256 _purchaseTokenAmount, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong, , // triggerPrice , // triggerAboveThreshold // executionFee ) = IOrderBook(orderBook).getIncreaseOrder(_account, _orderIndex); _validateMaxGlobalSize(_indexToken, _isLong, _sizeDelta); if (!shouldValidateIncreaseOrder) { return; } // shorts are okay if (!_isLong) { return; } // if the position size is not increasing, this is a collateral deposit require(_sizeDelta > 0, "PositionManager: long deposit"); IVault _vault = IVault(vault); (uint256 size, uint256 collateral, , , , , , ) = _vault.getPosition(_account, _collateralToken, _indexToken, _isLong); // if there is no existing position, do not charge a fee if (size == 0) { return; } uint256 nextSize = size.add(_sizeDelta); uint256 collateralDelta = _vault.tokenToUsdMin(_purchaseToken, _purchaseTokenAmount); uint256 nextCollateral = collateral.add(collateralDelta); uint256 prevLeverage = size.mul(BASIS_POINTS_DIVISOR).div(collateral); // allow for a maximum of a increasePositionBufferBps decrease since there might be some swap fees taken from the collateral uint256 nextLeverageWithBuffer = nextSize.mul(BASIS_POINTS_DIVISOR + increasePositionBufferBps).div(nextCollateral); require(nextLeverageWithBuffer >= prevLeverage, "PositionManager: long leverage decrease"); } }
contracts/core/interfaces/IBasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IBasePositionManager { function maxGlobalLongSizes(address _token) external view returns (uint256); function maxGlobalShortSizes(address _token) external view returns (uint256); }
contracts/referrals/interfaces/IReferralStorage.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IReferralStorage { function codeOwners(bytes32 _code) external view returns (address); function traderReferralCodes(address _account) external view returns (bytes32); function referrerDiscountShares(address _account) external view returns (uint256); function referrerTiers(address _account) external view returns (uint256); function getTraderReferralInfo(address _account) external view returns (bytes32, address); function setTraderReferralCode(address _account, bytes32 _code) external; function setTier(uint256 _tierId, uint256 _totalRebate, uint256 _discountShare) external; function setReferrerTier(address _referrer, uint256 _tierId) external; function govSetCodeOwner(bytes32 _code, address _newAccount) external; }
contracts/tokens/interfaces/IWETH.sol
//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; }
contracts/access/Governable.sol
// 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; } }
contracts/core/BasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../libraries/math/SafeMath.sol"; import "../libraries/token/IERC20.sol"; import "../tokens/interfaces/IWETH.sol"; import "../libraries/token/SafeERC20.sol"; import "../libraries/utils/Address.sol"; import "../libraries/utils/ReentrancyGuard.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IShortsTracker.sol"; import "./interfaces/IOrderBook.sol"; import "./interfaces/IBasePositionManager.sol"; import "../access/Governable.sol"; import "../peripherals/interfaces/ITimelock.sol"; import "../referrals/interfaces/IReferralStorage.sol"; contract BasePositionManager is IBasePositionManager, ReentrancyGuard, Governable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address payable; uint256 public constant BASIS_POINTS_DIVISOR = 10000; address public admin; address public vault; address public shortsTracker; address public router; address public weth; // to prevent using the deposit and withdrawal of collateral as a zero fee swap, // there is a small depositFee charged if a collateral deposit results in the decrease // of leverage for an existing position // increasePositionBufferBps allows for a small amount of decrease of leverage uint256 public depositFee; uint256 public increasePositionBufferBps = 100; address public referralStorage; mapping (address => uint256) public feeReserves; mapping (address => uint256) public override maxGlobalLongSizes; mapping (address => uint256) public override maxGlobalShortSizes; event SetDepositFee(uint256 depositFee); event SetIncreasePositionBufferBps(uint256 increasePositionBufferBps); event SetReferralStorage(address referralStorage); event SetAdmin(address admin); event WithdrawFees(address token, address receiver, uint256 amount); event SetMaxGlobalSizes( address[] tokens, uint256[] longSizes, uint256[] shortSizes ); event IncreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); event DecreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); modifier onlyAdmin() { require(msg.sender == admin, "BasePositionManager: forbidden"); _; } constructor( address _vault, address _router, address _shortsTracker, address _weth, uint256 _depositFee ) public { vault = _vault; router = _router; weth = _weth; depositFee = _depositFee; shortsTracker = _shortsTracker; admin = msg.sender; } receive() external payable { require(msg.sender == weth, "BasePositionManager: invalid sender"); } function setAdmin(address _admin) external onlyGov { admin = _admin; emit SetAdmin(_admin); } function setDepositFee(uint256 _depositFee) external onlyAdmin { depositFee = _depositFee; emit SetDepositFee(_depositFee); } function setIncreasePositionBufferBps(uint256 _increasePositionBufferBps) external onlyAdmin { increasePositionBufferBps = _increasePositionBufferBps; emit SetIncreasePositionBufferBps(_increasePositionBufferBps); } function setReferralStorage(address _referralStorage) external onlyAdmin { referralStorage = _referralStorage; emit SetReferralStorage(_referralStorage); } function setMaxGlobalSizes( address[] memory _tokens, uint256[] memory _longSizes, uint256[] memory _shortSizes ) external onlyAdmin { for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; maxGlobalLongSizes[token] = _longSizes[i]; maxGlobalShortSizes[token] = _shortSizes[i]; } emit SetMaxGlobalSizes(_tokens, _longSizes, _shortSizes); } function withdrawFees(address _token, address _receiver) external onlyAdmin { uint256 amount = feeReserves[_token]; if (amount == 0) { return; } feeReserves[_token] = 0; IERC20(_token).safeTransfer(_receiver, amount); emit WithdrawFees(_token, _receiver, amount); } function approve(address _token, address _spender, uint256 _amount) external onlyGov { IERC20(_token).approve(_spender, _amount); } function sendValue(address payable _receiver, uint256 _amount) external onlyGov { _receiver.sendValue(_amount); } function _validateMaxGlobalSize(address _indexToken, bool _isLong, uint256 _sizeDelta) internal view { if (_sizeDelta == 0) { return; } if (_isLong) { uint256 maxGlobalLongSize = maxGlobalLongSizes[_indexToken]; if (maxGlobalLongSize > 0 && IVault(vault).guaranteedUsd(_indexToken).add(_sizeDelta) > maxGlobalLongSize) { revert("BasePositionManager: max global longs exceeded"); } } else { uint256 maxGlobalShortSize = maxGlobalShortSizes[_indexToken]; if (maxGlobalShortSize > 0 && IVault(vault).globalShortSizes(_indexToken).add(_sizeDelta) > maxGlobalShortSize) { revert("BasePositionManager: max global shorts exceeded"); } } } function _increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong, uint256 _price) internal { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMaxPrice(_indexToken) : IVault(_vault).getMinPrice(_indexToken); if (_isLong) { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } else { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } _validateMaxGlobalSize(_indexToken, _isLong, _sizeDelta); address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, true); ITimelock(timelock).enableLeverage(_vault); IRouter(router).pluginIncreasePosition(_account, _collateralToken, _indexToken, _sizeDelta, _isLong); ITimelock(timelock).disableLeverage(_vault); _emitIncreasePositionReferral(_account, _sizeDelta); } function _decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price) internal returns (uint256) { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMinPrice(_indexToken) : IVault(_vault).getMaxPrice(_indexToken); if (_isLong) { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } else { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, false); ITimelock(timelock).enableLeverage(_vault); uint256 amountOut = IRouter(router).pluginDecreasePosition(_account, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, _receiver); ITimelock(timelock).disableLeverage(_vault); _emitDecreasePositionReferral(_account, _sizeDelta); return amountOut; } function _emitIncreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); emit IncreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _emitDecreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); if (referralCode == bytes32(0)) { return; } emit DecreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _swap(address[] memory _path, uint256 _minOut, address _receiver) internal returns (uint256) { if (_path.length == 2) { return _vaultSwap(_path[0], _path[1], _minOut, _receiver); } revert("BasePositionManager: invalid _path.length"); } function _vaultSwap(address _tokenIn, address _tokenOut, uint256 _minOut, address _receiver) internal returns (uint256) { uint256 amountOut = IVault(vault).swap(_tokenIn, _tokenOut, _receiver); require(amountOut >= _minOut, "BasePositionManager: insufficient amountOut"); return amountOut; } function _transferInETH() internal { if (msg.value != 0) { IWETH(weth).deposit{value: msg.value}(); } } function _transferOutETHWithGasLimitIgnoreFail(uint256 _amountOut, address payable _receiver) internal { IWETH(weth).withdraw(_amountOut); // use `send` instead of `transfer` to not revert whole transaction in case ETH transfer was failed // it has limit of 2300 gas // this is to avoid front-running _receiver.send(_amountOut); } function _collectFees( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal returns (uint256) { bool shouldDeductFee = _shouldDeductFee( _account, _path, _amountIn, _indexToken, _isLong, _sizeDelta ); if (shouldDeductFee) { uint256 afterFeeAmount = _amountIn.mul(BASIS_POINTS_DIVISOR.sub(depositFee)).div(BASIS_POINTS_DIVISOR); uint256 feeAmount = _amountIn.sub(afterFeeAmount); address feeToken = _path[_path.length - 1]; feeReserves[feeToken] = feeReserves[feeToken].add(feeAmount); return afterFeeAmount; } return _amountIn; } function _shouldDeductFee( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal view returns (bool) { // if the position is a short, do not charge a fee if (!_isLong) { return false; } // if the position size is not increasing, this is a collateral deposit if (_sizeDelta == 0) { return true; } address collateralToken = _path[_path.length - 1]; IVault _vault = IVault(vault); (uint256 size, uint256 collateral, , , , , , ) = _vault.getPosition(_account, collateralToken, _indexToken, _isLong); // if there is no existing position, do not charge a fee if (size == 0) { return false; } uint256 nextSize = size.add(_sizeDelta); uint256 collateralDelta = _vault.tokenToUsdMin(collateralToken, _amountIn); uint256 nextCollateral = collateral.add(collateralDelta); uint256 prevLeverage = size.mul(BASIS_POINTS_DIVISOR).div(collateral); // allow for a maximum of a increasePositionBufferBps decrease since there might be some swap fees taken from the collateral uint256 nextLeverage = nextSize.mul(BASIS_POINTS_DIVISOR + increasePositionBufferBps).div(nextCollateral); // deduct a fee if the leverage is decreased return nextLeverage < prevLeverage; } }
contracts/core/interfaces/IOrderBook.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IOrderBook { function getSwapOrder(address _account, uint256 _orderIndex) external view returns ( address path0, address path1, address path2, uint256 amountIn, uint256 minOut, uint256 triggerRatio, bool triggerAboveThreshold, bool shouldUnwrap, uint256 executionFee ); function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns ( address purchaseToken, uint256 purchaseTokenAmount, address collateralToken, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns ( address collateralToken, uint256 collateralDelta, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function executeSwapOrder(address, uint256, address payable) external; function executeDecreaseOrder(address, uint256, address payable) external; function executeIncreaseOrder(address, uint256, address payable) external; }
contracts/core/interfaces/IRouter.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRouter { function addPlugin(address _plugin) external; function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external; function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external; function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256); function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external; }
contracts/core/interfaces/IShortsTracker.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IShortsTracker { function isGlobalShortDataReady() external view returns (bool); function globalShortAveragePrices(address _token) external view returns (uint256); function getNextGlobalShortData( address _account, address _collateralToken, address _indexToken, uint256 _nextPrice, uint256 _sizeDelta, bool _isIncrease ) external view returns (uint256, uint256); function updateGlobalShortData( address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta, uint256 _markPrice, bool _isIncrease ) external; function setIsGlobalShortDataReady(bool value) external; function setInitData(address[] calldata _tokens, uint256[] calldata _averagePrices) external; }
contracts/core/interfaces/IVault.sol
// 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 usdk() 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 getTargetUsdkAmount(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 setUsdkAmount(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 _maxUsdkAmount, 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 buyUSDK(address _token, address _receiver) external returns (uint256); function sellUSDK(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 _usdkDelta, 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 usdkAmounts(address _token) external view returns (uint256); function maxUsdkAmounts(address _token) external view returns (uint256); function getRedemptionAmount(address _token, uint256 _usdkAmount) 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); }
contracts/core/interfaces/IVaultUtils.sol
// 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 getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256); function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256); }
contracts/libraries/math/SafeMath.sol
// 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; } }
contracts/libraries/token/IERC20.sol
// 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); }
contracts/libraries/token/SafeERC20.sol
// 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"); } } }
contracts/libraries/utils/Address.sol
// 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); } } } }
contracts/libraries/utils/ReentrancyGuard.sol
// 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; } }
contracts/peripherals/interfaces/ITimelock.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ITimelock { function setAdmin(address _admin) external; function enableLeverage(address _vault) external; function disableLeverage(address _vault) external; function setIsLeverageEnabled(address _vault, bool _isLeverageEnabled) external; function signalSetGov(address _target, address _gov) external; }
contracts/core/interfaces/IBasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IBasePositionManager { function maxGlobalLongSizes(address _token) external view returns (uint256); function maxGlobalShortSizes(address _token) external view returns (uint256); }
contracts/referrals/interfaces/IReferralStorage.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IReferralStorage { function codeOwners(bytes32 _code) external view returns (address); function traderReferralCodes(address _account) external view returns (bytes32); function referrerDiscountShares(address _account) external view returns (uint256); function referrerTiers(address _account) external view returns (uint256); function getTraderReferralInfo(address _account) external view returns (bytes32, address); function setTraderReferralCode(address _account, bytes32 _code) external; function setTier(uint256 _tierId, uint256 _totalRebate, uint256 _discountShare) external; function setReferrerTier(address _referrer, uint256 _tierId) external; function govSetCodeOwner(bytes32 _code, address _newAccount) external; }
contracts/tokens/interfaces/IWETH.sol
//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; }
contracts/access/Governable.sol
// 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; } }
contracts/core/BasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../libraries/math/SafeMath.sol"; import "../libraries/token/IERC20.sol"; import "../tokens/interfaces/IWETH.sol"; import "../libraries/token/SafeERC20.sol"; import "../libraries/utils/Address.sol"; import "../libraries/utils/ReentrancyGuard.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IShortsTracker.sol"; import "./interfaces/IOrderBook.sol"; import "./interfaces/IBasePositionManager.sol"; import "../access/Governable.sol"; import "../peripherals/interfaces/ITimelock.sol"; import "../referrals/interfaces/IReferralStorage.sol"; contract BasePositionManager is IBasePositionManager, ReentrancyGuard, Governable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address payable; uint256 public constant BASIS_POINTS_DIVISOR = 10000; address public admin; address public vault; address public shortsTracker; address public router; address public weth; // to prevent using the deposit and withdrawal of collateral as a zero fee swap, // there is a small depositFee charged if a collateral deposit results in the decrease // of leverage for an existing position // increasePositionBufferBps allows for a small amount of decrease of leverage uint256 public depositFee; uint256 public increasePositionBufferBps = 100; address public referralStorage; mapping (address => uint256) public feeReserves; mapping (address => uint256) public override maxGlobalLongSizes; mapping (address => uint256) public override maxGlobalShortSizes; event SetDepositFee(uint256 depositFee); event SetIncreasePositionBufferBps(uint256 increasePositionBufferBps); event SetReferralStorage(address referralStorage); event SetAdmin(address admin); event WithdrawFees(address token, address receiver, uint256 amount); event SetMaxGlobalSizes( address[] tokens, uint256[] longSizes, uint256[] shortSizes ); event IncreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); event DecreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); modifier onlyAdmin() { require(msg.sender == admin, "BasePositionManager: forbidden"); _; } constructor( address _vault, address _router, address _shortsTracker, address _weth, uint256 _depositFee ) public { vault = _vault; router = _router; weth = _weth; depositFee = _depositFee; shortsTracker = _shortsTracker; admin = msg.sender; } receive() external payable { require(msg.sender == weth, "BasePositionManager: invalid sender"); } function setAdmin(address _admin) external onlyGov { admin = _admin; emit SetAdmin(_admin); } function setDepositFee(uint256 _depositFee) external onlyAdmin { depositFee = _depositFee; emit SetDepositFee(_depositFee); } function setIncreasePositionBufferBps(uint256 _increasePositionBufferBps) external onlyAdmin { increasePositionBufferBps = _increasePositionBufferBps; emit SetIncreasePositionBufferBps(_increasePositionBufferBps); } function setReferralStorage(address _referralStorage) external onlyAdmin { referralStorage = _referralStorage; emit SetReferralStorage(_referralStorage); } function setMaxGlobalSizes( address[] memory _tokens, uint256[] memory _longSizes, uint256[] memory _shortSizes ) external onlyAdmin { for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; maxGlobalLongSizes[token] = _longSizes[i]; maxGlobalShortSizes[token] = _shortSizes[i]; } emit SetMaxGlobalSizes(_tokens, _longSizes, _shortSizes); } function withdrawFees(address _token, address _receiver) external onlyAdmin { uint256 amount = feeReserves[_token]; if (amount == 0) { return; } feeReserves[_token] = 0; IERC20(_token).safeTransfer(_receiver, amount); emit WithdrawFees(_token, _receiver, amount); } function approve(address _token, address _spender, uint256 _amount) external onlyGov { IERC20(_token).approve(_spender, _amount); } function sendValue(address payable _receiver, uint256 _amount) external onlyGov { _receiver.sendValue(_amount); } function _validateMaxGlobalSize(address _indexToken, bool _isLong, uint256 _sizeDelta) internal view { if (_sizeDelta == 0) { return; } if (_isLong) { uint256 maxGlobalLongSize = maxGlobalLongSizes[_indexToken]; if (maxGlobalLongSize > 0 && IVault(vault).guaranteedUsd(_indexToken).add(_sizeDelta) > maxGlobalLongSize) { revert("BasePositionManager: max global longs exceeded"); } } else { uint256 maxGlobalShortSize = maxGlobalShortSizes[_indexToken]; if (maxGlobalShortSize > 0 && IVault(vault).globalShortSizes(_indexToken).add(_sizeDelta) > maxGlobalShortSize) { revert("BasePositionManager: max global shorts exceeded"); } } } function _increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong, uint256 _price) internal { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMaxPrice(_indexToken) : IVault(_vault).getMinPrice(_indexToken); if (_isLong) { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } else { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } _validateMaxGlobalSize(_indexToken, _isLong, _sizeDelta); address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, true); ITimelock(timelock).enableLeverage(_vault); IRouter(router).pluginIncreasePosition(_account, _collateralToken, _indexToken, _sizeDelta, _isLong); ITimelock(timelock).disableLeverage(_vault); _emitIncreasePositionReferral(_account, _sizeDelta); } function _decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price) internal returns (uint256) { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMinPrice(_indexToken) : IVault(_vault).getMaxPrice(_indexToken); if (_isLong) { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } else { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, false); ITimelock(timelock).enableLeverage(_vault); uint256 amountOut = IRouter(router).pluginDecreasePosition(_account, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, _receiver); ITimelock(timelock).disableLeverage(_vault); _emitDecreasePositionReferral(_account, _sizeDelta); return amountOut; } function _emitIncreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); emit IncreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _emitDecreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); if (referralCode == bytes32(0)) { return; } emit DecreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _swap(address[] memory _path, uint256 _minOut, address _receiver) internal returns (uint256) { if (_path.length == 2) { return _vaultSwap(_path[0], _path[1], _minOut, _receiver); } revert("BasePositionManager: invalid _path.length"); } function _vaultSwap(address _tokenIn, address _tokenOut, uint256 _minOut, address _receiver) internal returns (uint256) { uint256 amountOut = IVault(vault).swap(_tokenIn, _tokenOut, _receiver); require(amountOut >= _minOut, "BasePositionManager: insufficient amountOut"); return amountOut; } function _transferInETH() internal { if (msg.value != 0) { IWETH(weth).deposit{value: msg.value}(); } } function _transferOutETHWithGasLimitIgnoreFail(uint256 _amountOut, address payable _receiver) internal { IWETH(weth).withdraw(_amountOut); // use `send` instead of `transfer` to not revert whole transaction in case ETH transfer was failed // it has limit of 2300 gas // this is to avoid front-running _receiver.send(_amountOut); } function _collectFees( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal returns (uint256) { bool shouldDeductFee = _shouldDeductFee( _account, _path, _amountIn, _indexToken, _isLong, _sizeDelta ); if (shouldDeductFee) { uint256 afterFeeAmount = _amountIn.mul(BASIS_POINTS_DIVISOR.sub(depositFee)).div(BASIS_POINTS_DIVISOR); uint256 feeAmount = _amountIn.sub(afterFeeAmount); address feeToken = _path[_path.length - 1]; feeReserves[feeToken] = feeReserves[feeToken].add(feeAmount); return afterFeeAmount; } return _amountIn; } function _shouldDeductFee( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal view returns (bool) { // if the position is a short, do not charge a fee if (!_isLong) { return false; } // if the position size is not increasing, this is a collateral deposit if (_sizeDelta == 0) { return true; } address collateralToken = _path[_path.length - 1]; IVault _vault = IVault(vault); (uint256 size, uint256 collateral, , , , , , ) = _vault.getPosition(_account, collateralToken, _indexToken, _isLong); // if there is no existing position, do not charge a fee if (size == 0) { return false; } uint256 nextSize = size.add(_sizeDelta); uint256 collateralDelta = _vault.tokenToUsdMin(collateralToken, _amountIn); uint256 nextCollateral = collateral.add(collateralDelta); uint256 prevLeverage = size.mul(BASIS_POINTS_DIVISOR).div(collateral); // allow for a maximum of a increasePositionBufferBps decrease since there might be some swap fees taken from the collateral uint256 nextLeverage = nextSize.mul(BASIS_POINTS_DIVISOR + increasePositionBufferBps).div(nextCollateral); // deduct a fee if the leverage is decreased return nextLeverage < prevLeverage; } }
contracts/core/interfaces/IOrderBook.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IOrderBook { function getSwapOrder(address _account, uint256 _orderIndex) external view returns ( address path0, address path1, address path2, uint256 amountIn, uint256 minOut, uint256 triggerRatio, bool triggerAboveThreshold, bool shouldUnwrap, uint256 executionFee ); function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns ( address purchaseToken, uint256 purchaseTokenAmount, address collateralToken, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns ( address collateralToken, uint256 collateralDelta, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function executeSwapOrder(address, uint256, address payable) external; function executeDecreaseOrder(address, uint256, address payable) external; function executeIncreaseOrder(address, uint256, address payable) external; }
contracts/core/interfaces/IRouter.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRouter { function addPlugin(address _plugin) external; function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external; function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external; function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256); function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external; }
contracts/core/interfaces/IShortsTracker.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IShortsTracker { function isGlobalShortDataReady() external view returns (bool); function globalShortAveragePrices(address _token) external view returns (uint256); function getNextGlobalShortData( address _account, address _collateralToken, address _indexToken, uint256 _nextPrice, uint256 _sizeDelta, bool _isIncrease ) external view returns (uint256, uint256); function updateGlobalShortData( address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta, uint256 _markPrice, bool _isIncrease ) external; function setIsGlobalShortDataReady(bool value) external; function setInitData(address[] calldata _tokens, uint256[] calldata _averagePrices) external; }
contracts/core/interfaces/IVault.sol
// 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 usdk() 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 getTargetUsdkAmount(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 setUsdkAmount(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 _maxUsdkAmount, 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 buyUSDK(address _token, address _receiver) external returns (uint256); function sellUSDK(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 _usdkDelta, 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 usdkAmounts(address _token) external view returns (uint256); function maxUsdkAmounts(address _token) external view returns (uint256); function getRedemptionAmount(address _token, uint256 _usdkAmount) 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); }
contracts/core/interfaces/IVaultUtils.sol
// 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 getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256); function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256); }
contracts/libraries/math/SafeMath.sol
// 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; } }
contracts/libraries/token/IERC20.sol
// 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); }
contracts/libraries/token/SafeERC20.sol
// 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"); } } }
contracts/libraries/utils/Address.sol
// 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); } } } }
contracts/libraries/utils/ReentrancyGuard.sol
// 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; } }
contracts/peripherals/interfaces/ITimelock.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ITimelock { function setAdmin(address _admin) external; function enableLeverage(address _vault) external; function disableLeverage(address _vault) external; function setIsLeverageEnabled(address _vault, bool _isLeverageEnabled) external; function signalSetGov(address _target, address _gov) external; }
contracts/core/interfaces/IBasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IBasePositionManager { function maxGlobalLongSizes(address _token) external view returns (uint256); function maxGlobalShortSizes(address _token) external view returns (uint256); }
contracts/referrals/interfaces/IReferralStorage.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IReferralStorage { function codeOwners(bytes32 _code) external view returns (address); function traderReferralCodes(address _account) external view returns (bytes32); function referrerDiscountShares(address _account) external view returns (uint256); function referrerTiers(address _account) external view returns (uint256); function getTraderReferralInfo(address _account) external view returns (bytes32, address); function setTraderReferralCode(address _account, bytes32 _code) external; function setTier(uint256 _tierId, uint256 _totalRebate, uint256 _discountShare) external; function setReferrerTier(address _referrer, uint256 _tierId) external; function govSetCodeOwner(bytes32 _code, address _newAccount) external; }
contracts/tokens/interfaces/IWETH.sol
//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; }
contracts/access/Governable.sol
// 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; } }
contracts/core/BasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../libraries/math/SafeMath.sol"; import "../libraries/token/IERC20.sol"; import "../tokens/interfaces/IWETH.sol"; import "../libraries/token/SafeERC20.sol"; import "../libraries/utils/Address.sol"; import "../libraries/utils/ReentrancyGuard.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IShortsTracker.sol"; import "./interfaces/IOrderBook.sol"; import "./interfaces/IBasePositionManager.sol"; import "../access/Governable.sol"; import "../peripherals/interfaces/ITimelock.sol"; import "../referrals/interfaces/IReferralStorage.sol"; contract BasePositionManager is IBasePositionManager, ReentrancyGuard, Governable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address payable; uint256 public constant BASIS_POINTS_DIVISOR = 10000; address public admin; address public vault; address public shortsTracker; address public router; address public weth; // to prevent using the deposit and withdrawal of collateral as a zero fee swap, // there is a small depositFee charged if a collateral deposit results in the decrease // of leverage for an existing position // increasePositionBufferBps allows for a small amount of decrease of leverage uint256 public depositFee; uint256 public increasePositionBufferBps = 100; address public referralStorage; mapping (address => uint256) public feeReserves; mapping (address => uint256) public override maxGlobalLongSizes; mapping (address => uint256) public override maxGlobalShortSizes; event SetDepositFee(uint256 depositFee); event SetIncreasePositionBufferBps(uint256 increasePositionBufferBps); event SetReferralStorage(address referralStorage); event SetAdmin(address admin); event WithdrawFees(address token, address receiver, uint256 amount); event SetMaxGlobalSizes( address[] tokens, uint256[] longSizes, uint256[] shortSizes ); event IncreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); event DecreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); modifier onlyAdmin() { require(msg.sender == admin, "BasePositionManager: forbidden"); _; } constructor( address _vault, address _router, address _shortsTracker, address _weth, uint256 _depositFee ) public { vault = _vault; router = _router; weth = _weth; depositFee = _depositFee; shortsTracker = _shortsTracker; admin = msg.sender; } receive() external payable { require(msg.sender == weth, "BasePositionManager: invalid sender"); } function setAdmin(address _admin) external onlyGov { admin = _admin; emit SetAdmin(_admin); } function setDepositFee(uint256 _depositFee) external onlyAdmin { depositFee = _depositFee; emit SetDepositFee(_depositFee); } function setIncreasePositionBufferBps(uint256 _increasePositionBufferBps) external onlyAdmin { increasePositionBufferBps = _increasePositionBufferBps; emit SetIncreasePositionBufferBps(_increasePositionBufferBps); } function setReferralStorage(address _referralStorage) external onlyAdmin { referralStorage = _referralStorage; emit SetReferralStorage(_referralStorage); } function setMaxGlobalSizes( address[] memory _tokens, uint256[] memory _longSizes, uint256[] memory _shortSizes ) external onlyAdmin { for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; maxGlobalLongSizes[token] = _longSizes[i]; maxGlobalShortSizes[token] = _shortSizes[i]; } emit SetMaxGlobalSizes(_tokens, _longSizes, _shortSizes); } function withdrawFees(address _token, address _receiver) external onlyAdmin { uint256 amount = feeReserves[_token]; if (amount == 0) { return; } feeReserves[_token] = 0; IERC20(_token).safeTransfer(_receiver, amount); emit WithdrawFees(_token, _receiver, amount); } function approve(address _token, address _spender, uint256 _amount) external onlyGov { IERC20(_token).approve(_spender, _amount); } function sendValue(address payable _receiver, uint256 _amount) external onlyGov { _receiver.sendValue(_amount); } function _validateMaxGlobalSize(address _indexToken, bool _isLong, uint256 _sizeDelta) internal view { if (_sizeDelta == 0) { return; } if (_isLong) { uint256 maxGlobalLongSize = maxGlobalLongSizes[_indexToken]; if (maxGlobalLongSize > 0 && IVault(vault).guaranteedUsd(_indexToken).add(_sizeDelta) > maxGlobalLongSize) { revert("BasePositionManager: max global longs exceeded"); } } else { uint256 maxGlobalShortSize = maxGlobalShortSizes[_indexToken]; if (maxGlobalShortSize > 0 && IVault(vault).globalShortSizes(_indexToken).add(_sizeDelta) > maxGlobalShortSize) { revert("BasePositionManager: max global shorts exceeded"); } } } function _increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong, uint256 _price) internal { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMaxPrice(_indexToken) : IVault(_vault).getMinPrice(_indexToken); if (_isLong) { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } else { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } _validateMaxGlobalSize(_indexToken, _isLong, _sizeDelta); address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, true); ITimelock(timelock).enableLeverage(_vault); IRouter(router).pluginIncreasePosition(_account, _collateralToken, _indexToken, _sizeDelta, _isLong); ITimelock(timelock).disableLeverage(_vault); _emitIncreasePositionReferral(_account, _sizeDelta); } function _decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price) internal returns (uint256) { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMinPrice(_indexToken) : IVault(_vault).getMaxPrice(_indexToken); if (_isLong) { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } else { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, false); ITimelock(timelock).enableLeverage(_vault); uint256 amountOut = IRouter(router).pluginDecreasePosition(_account, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, _receiver); ITimelock(timelock).disableLeverage(_vault); _emitDecreasePositionReferral(_account, _sizeDelta); return amountOut; } function _emitIncreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); emit IncreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _emitDecreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); if (referralCode == bytes32(0)) { return; } emit DecreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _swap(address[] memory _path, uint256 _minOut, address _receiver) internal returns (uint256) { if (_path.length == 2) { return _vaultSwap(_path[0], _path[1], _minOut, _receiver); } revert("BasePositionManager: invalid _path.length"); } function _vaultSwap(address _tokenIn, address _tokenOut, uint256 _minOut, address _receiver) internal returns (uint256) { uint256 amountOut = IVault(vault).swap(_tokenIn, _tokenOut, _receiver); require(amountOut >= _minOut, "BasePositionManager: insufficient amountOut"); return amountOut; } function _transferInETH() internal { if (msg.value != 0) { IWETH(weth).deposit{value: msg.value}(); } } function _transferOutETHWithGasLimitIgnoreFail(uint256 _amountOut, address payable _receiver) internal { IWETH(weth).withdraw(_amountOut); // use `send` instead of `transfer` to not revert whole transaction in case ETH transfer was failed // it has limit of 2300 gas // this is to avoid front-running _receiver.send(_amountOut); } function _collectFees( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal returns (uint256) { bool shouldDeductFee = _shouldDeductFee( _account, _path, _amountIn, _indexToken, _isLong, _sizeDelta ); if (shouldDeductFee) { uint256 afterFeeAmount = _amountIn.mul(BASIS_POINTS_DIVISOR.sub(depositFee)).div(BASIS_POINTS_DIVISOR); uint256 feeAmount = _amountIn.sub(afterFeeAmount); address feeToken = _path[_path.length - 1]; feeReserves[feeToken] = feeReserves[feeToken].add(feeAmount); return afterFeeAmount; } return _amountIn; } function _shouldDeductFee( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal view returns (bool) { // if the position is a short, do not charge a fee if (!_isLong) { return false; } // if the position size is not increasing, this is a collateral deposit if (_sizeDelta == 0) { return true; } address collateralToken = _path[_path.length - 1]; IVault _vault = IVault(vault); (uint256 size, uint256 collateral, , , , , , ) = _vault.getPosition(_account, collateralToken, _indexToken, _isLong); // if there is no existing position, do not charge a fee if (size == 0) { return false; } uint256 nextSize = size.add(_sizeDelta); uint256 collateralDelta = _vault.tokenToUsdMin(collateralToken, _amountIn); uint256 nextCollateral = collateral.add(collateralDelta); uint256 prevLeverage = size.mul(BASIS_POINTS_DIVISOR).div(collateral); // allow for a maximum of a increasePositionBufferBps decrease since there might be some swap fees taken from the collateral uint256 nextLeverage = nextSize.mul(BASIS_POINTS_DIVISOR + increasePositionBufferBps).div(nextCollateral); // deduct a fee if the leverage is decreased return nextLeverage < prevLeverage; } }
contracts/core/interfaces/IOrderBook.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IOrderBook { function getSwapOrder(address _account, uint256 _orderIndex) external view returns ( address path0, address path1, address path2, uint256 amountIn, uint256 minOut, uint256 triggerRatio, bool triggerAboveThreshold, bool shouldUnwrap, uint256 executionFee ); function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns ( address purchaseToken, uint256 purchaseTokenAmount, address collateralToken, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns ( address collateralToken, uint256 collateralDelta, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function executeSwapOrder(address, uint256, address payable) external; function executeDecreaseOrder(address, uint256, address payable) external; function executeIncreaseOrder(address, uint256, address payable) external; }
contracts/core/interfaces/IRouter.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRouter { function addPlugin(address _plugin) external; function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external; function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external; function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256); function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external; }
contracts/core/interfaces/IShortsTracker.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IShortsTracker { function isGlobalShortDataReady() external view returns (bool); function globalShortAveragePrices(address _token) external view returns (uint256); function getNextGlobalShortData( address _account, address _collateralToken, address _indexToken, uint256 _nextPrice, uint256 _sizeDelta, bool _isIncrease ) external view returns (uint256, uint256); function updateGlobalShortData( address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta, uint256 _markPrice, bool _isIncrease ) external; function setIsGlobalShortDataReady(bool value) external; function setInitData(address[] calldata _tokens, uint256[] calldata _averagePrices) external; }
contracts/core/interfaces/IVault.sol
// 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 usdk() 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 getTargetUsdkAmount(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 setUsdkAmount(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 _maxUsdkAmount, 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 buyUSDK(address _token, address _receiver) external returns (uint256); function sellUSDK(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 _usdkDelta, 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 usdkAmounts(address _token) external view returns (uint256); function maxUsdkAmounts(address _token) external view returns (uint256); function getRedemptionAmount(address _token, uint256 _usdkAmount) 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); }
contracts/core/interfaces/IVaultUtils.sol
// 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 getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256); function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256); }
contracts/libraries/math/SafeMath.sol
// 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; } }
contracts/libraries/token/IERC20.sol
// 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); }
contracts/libraries/token/SafeERC20.sol
// 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"); } } }
contracts/libraries/utils/Address.sol
// 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); } } } }
contracts/libraries/utils/ReentrancyGuard.sol
// 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; } }
contracts/peripherals/interfaces/ITimelock.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ITimelock { function setAdmin(address _admin) external; function enableLeverage(address _vault) external; function disableLeverage(address _vault) external; function setIsLeverageEnabled(address _vault, bool _isLeverageEnabled) external; function signalSetGov(address _target, address _gov) external; }
contracts/core/interfaces/IBasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IBasePositionManager { function maxGlobalLongSizes(address _token) external view returns (uint256); function maxGlobalShortSizes(address _token) external view returns (uint256); }
contracts/referrals/interfaces/IReferralStorage.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IReferralStorage { function codeOwners(bytes32 _code) external view returns (address); function traderReferralCodes(address _account) external view returns (bytes32); function referrerDiscountShares(address _account) external view returns (uint256); function referrerTiers(address _account) external view returns (uint256); function getTraderReferralInfo(address _account) external view returns (bytes32, address); function setTraderReferralCode(address _account, bytes32 _code) external; function setTier(uint256 _tierId, uint256 _totalRebate, uint256 _discountShare) external; function setReferrerTier(address _referrer, uint256 _tierId) external; function govSetCodeOwner(bytes32 _code, address _newAccount) external; }
contracts/tokens/interfaces/IWETH.sol
//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; }
contracts/access/Governable.sol
// 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; } }
contracts/core/BasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../libraries/math/SafeMath.sol"; import "../libraries/token/IERC20.sol"; import "../tokens/interfaces/IWETH.sol"; import "../libraries/token/SafeERC20.sol"; import "../libraries/utils/Address.sol"; import "../libraries/utils/ReentrancyGuard.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IShortsTracker.sol"; import "./interfaces/IOrderBook.sol"; import "./interfaces/IBasePositionManager.sol"; import "../access/Governable.sol"; import "../peripherals/interfaces/ITimelock.sol"; import "../referrals/interfaces/IReferralStorage.sol"; contract BasePositionManager is IBasePositionManager, ReentrancyGuard, Governable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address payable; uint256 public constant BASIS_POINTS_DIVISOR = 10000; address public admin; address public vault; address public shortsTracker; address public router; address public weth; // to prevent using the deposit and withdrawal of collateral as a zero fee swap, // there is a small depositFee charged if a collateral deposit results in the decrease // of leverage for an existing position // increasePositionBufferBps allows for a small amount of decrease of leverage uint256 public depositFee; uint256 public increasePositionBufferBps = 100; address public referralStorage; mapping (address => uint256) public feeReserves; mapping (address => uint256) public override maxGlobalLongSizes; mapping (address => uint256) public override maxGlobalShortSizes; event SetDepositFee(uint256 depositFee); event SetIncreasePositionBufferBps(uint256 increasePositionBufferBps); event SetReferralStorage(address referralStorage); event SetAdmin(address admin); event WithdrawFees(address token, address receiver, uint256 amount); event SetMaxGlobalSizes( address[] tokens, uint256[] longSizes, uint256[] shortSizes ); event IncreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); event DecreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); modifier onlyAdmin() { require(msg.sender == admin, "BasePositionManager: forbidden"); _; } constructor( address _vault, address _router, address _shortsTracker, address _weth, uint256 _depositFee ) public { vault = _vault; router = _router; weth = _weth; depositFee = _depositFee; shortsTracker = _shortsTracker; admin = msg.sender; } receive() external payable { require(msg.sender == weth, "BasePositionManager: invalid sender"); } function setAdmin(address _admin) external onlyGov { admin = _admin; emit SetAdmin(_admin); } function setDepositFee(uint256 _depositFee) external onlyAdmin { depositFee = _depositFee; emit SetDepositFee(_depositFee); } function setIncreasePositionBufferBps(uint256 _increasePositionBufferBps) external onlyAdmin { increasePositionBufferBps = _increasePositionBufferBps; emit SetIncreasePositionBufferBps(_increasePositionBufferBps); } function setReferralStorage(address _referralStorage) external onlyAdmin { referralStorage = _referralStorage; emit SetReferralStorage(_referralStorage); } function setMaxGlobalSizes( address[] memory _tokens, uint256[] memory _longSizes, uint256[] memory _shortSizes ) external onlyAdmin { for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; maxGlobalLongSizes[token] = _longSizes[i]; maxGlobalShortSizes[token] = _shortSizes[i]; } emit SetMaxGlobalSizes(_tokens, _longSizes, _shortSizes); } function withdrawFees(address _token, address _receiver) external onlyAdmin { uint256 amount = feeReserves[_token]; if (amount == 0) { return; } feeReserves[_token] = 0; IERC20(_token).safeTransfer(_receiver, amount); emit WithdrawFees(_token, _receiver, amount); } function approve(address _token, address _spender, uint256 _amount) external onlyGov { IERC20(_token).approve(_spender, _amount); } function sendValue(address payable _receiver, uint256 _amount) external onlyGov { _receiver.sendValue(_amount); } function _validateMaxGlobalSize(address _indexToken, bool _isLong, uint256 _sizeDelta) internal view { if (_sizeDelta == 0) { return; } if (_isLong) { uint256 maxGlobalLongSize = maxGlobalLongSizes[_indexToken]; if (maxGlobalLongSize > 0 && IVault(vault).guaranteedUsd(_indexToken).add(_sizeDelta) > maxGlobalLongSize) { revert("BasePositionManager: max global longs exceeded"); } } else { uint256 maxGlobalShortSize = maxGlobalShortSizes[_indexToken]; if (maxGlobalShortSize > 0 && IVault(vault).globalShortSizes(_indexToken).add(_sizeDelta) > maxGlobalShortSize) { revert("BasePositionManager: max global shorts exceeded"); } } } function _increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong, uint256 _price) internal { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMaxPrice(_indexToken) : IVault(_vault).getMinPrice(_indexToken); if (_isLong) { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } else { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } _validateMaxGlobalSize(_indexToken, _isLong, _sizeDelta); address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, true); ITimelock(timelock).enableLeverage(_vault); IRouter(router).pluginIncreasePosition(_account, _collateralToken, _indexToken, _sizeDelta, _isLong); ITimelock(timelock).disableLeverage(_vault); _emitIncreasePositionReferral(_account, _sizeDelta); } function _decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price) internal returns (uint256) { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMinPrice(_indexToken) : IVault(_vault).getMaxPrice(_indexToken); if (_isLong) { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } else { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, false); ITimelock(timelock).enableLeverage(_vault); uint256 amountOut = IRouter(router).pluginDecreasePosition(_account, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, _receiver); ITimelock(timelock).disableLeverage(_vault); _emitDecreasePositionReferral(_account, _sizeDelta); return amountOut; } function _emitIncreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); emit IncreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _emitDecreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); if (referralCode == bytes32(0)) { return; } emit DecreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _swap(address[] memory _path, uint256 _minOut, address _receiver) internal returns (uint256) { if (_path.length == 2) { return _vaultSwap(_path[0], _path[1], _minOut, _receiver); } revert("BasePositionManager: invalid _path.length"); } function _vaultSwap(address _tokenIn, address _tokenOut, uint256 _minOut, address _receiver) internal returns (uint256) { uint256 amountOut = IVault(vault).swap(_tokenIn, _tokenOut, _receiver); require(amountOut >= _minOut, "BasePositionManager: insufficient amountOut"); return amountOut; } function _transferInETH() internal { if (msg.value != 0) { IWETH(weth).deposit{value: msg.value}(); } } function _transferOutETHWithGasLimitIgnoreFail(uint256 _amountOut, address payable _receiver) internal { IWETH(weth).withdraw(_amountOut); // use `send` instead of `transfer` to not revert whole transaction in case ETH transfer was failed // it has limit of 2300 gas // this is to avoid front-running _receiver.send(_amountOut); } function _collectFees( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal returns (uint256) { bool shouldDeductFee = _shouldDeductFee( _account, _path, _amountIn, _indexToken, _isLong, _sizeDelta ); if (shouldDeductFee) { uint256 afterFeeAmount = _amountIn.mul(BASIS_POINTS_DIVISOR.sub(depositFee)).div(BASIS_POINTS_DIVISOR); uint256 feeAmount = _amountIn.sub(afterFeeAmount); address feeToken = _path[_path.length - 1]; feeReserves[feeToken] = feeReserves[feeToken].add(feeAmount); return afterFeeAmount; } return _amountIn; } function _shouldDeductFee( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal view returns (bool) { // if the position is a short, do not charge a fee if (!_isLong) { return false; } // if the position size is not increasing, this is a collateral deposit if (_sizeDelta == 0) { return true; } address collateralToken = _path[_path.length - 1]; IVault _vault = IVault(vault); (uint256 size, uint256 collateral, , , , , , ) = _vault.getPosition(_account, collateralToken, _indexToken, _isLong); // if there is no existing position, do not charge a fee if (size == 0) { return false; } uint256 nextSize = size.add(_sizeDelta); uint256 collateralDelta = _vault.tokenToUsdMin(collateralToken, _amountIn); uint256 nextCollateral = collateral.add(collateralDelta); uint256 prevLeverage = size.mul(BASIS_POINTS_DIVISOR).div(collateral); // allow for a maximum of a increasePositionBufferBps decrease since there might be some swap fees taken from the collateral uint256 nextLeverage = nextSize.mul(BASIS_POINTS_DIVISOR + increasePositionBufferBps).div(nextCollateral); // deduct a fee if the leverage is decreased return nextLeverage < prevLeverage; } }
contracts/core/interfaces/IOrderBook.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IOrderBook { function getSwapOrder(address _account, uint256 _orderIndex) external view returns ( address path0, address path1, address path2, uint256 amountIn, uint256 minOut, uint256 triggerRatio, bool triggerAboveThreshold, bool shouldUnwrap, uint256 executionFee ); function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns ( address purchaseToken, uint256 purchaseTokenAmount, address collateralToken, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns ( address collateralToken, uint256 collateralDelta, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function executeSwapOrder(address, uint256, address payable) external; function executeDecreaseOrder(address, uint256, address payable) external; function executeIncreaseOrder(address, uint256, address payable) external; }
contracts/core/interfaces/IRouter.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRouter { function addPlugin(address _plugin) external; function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external; function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external; function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256); function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external; }
contracts/core/interfaces/IShortsTracker.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IShortsTracker { function isGlobalShortDataReady() external view returns (bool); function globalShortAveragePrices(address _token) external view returns (uint256); function getNextGlobalShortData( address _account, address _collateralToken, address _indexToken, uint256 _nextPrice, uint256 _sizeDelta, bool _isIncrease ) external view returns (uint256, uint256); function updateGlobalShortData( address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta, uint256 _markPrice, bool _isIncrease ) external; function setIsGlobalShortDataReady(bool value) external; function setInitData(address[] calldata _tokens, uint256[] calldata _averagePrices) external; }
contracts/core/interfaces/IVault.sol
// 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 usdk() 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 getTargetUsdkAmount(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 setUsdkAmount(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 _maxUsdkAmount, 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 buyUSDK(address _token, address _receiver) external returns (uint256); function sellUSDK(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 _usdkDelta, 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 usdkAmounts(address _token) external view returns (uint256); function maxUsdkAmounts(address _token) external view returns (uint256); function getRedemptionAmount(address _token, uint256 _usdkAmount) 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); }
contracts/core/interfaces/IVaultUtils.sol
// 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 getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256); function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256); }
contracts/libraries/math/SafeMath.sol
// 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; } }
contracts/libraries/token/IERC20.sol
// 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); }
contracts/libraries/token/SafeERC20.sol
// 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"); } } }
contracts/libraries/utils/Address.sol
// 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); } } } }
contracts/libraries/utils/ReentrancyGuard.sol
// 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; } }
contracts/peripherals/interfaces/ITimelock.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ITimelock { function setAdmin(address _admin) external; function enableLeverage(address _vault) external; function disableLeverage(address _vault) external; function setIsLeverageEnabled(address _vault, bool _isLeverageEnabled) external; function signalSetGov(address _target, address _gov) external; }
contracts/core/interfaces/IBasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IBasePositionManager { function maxGlobalLongSizes(address _token) external view returns (uint256); function maxGlobalShortSizes(address _token) external view returns (uint256); }
contracts/referrals/interfaces/IReferralStorage.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IReferralStorage { function codeOwners(bytes32 _code) external view returns (address); function traderReferralCodes(address _account) external view returns (bytes32); function referrerDiscountShares(address _account) external view returns (uint256); function referrerTiers(address _account) external view returns (uint256); function getTraderReferralInfo(address _account) external view returns (bytes32, address); function setTraderReferralCode(address _account, bytes32 _code) external; function setTier(uint256 _tierId, uint256 _totalRebate, uint256 _discountShare) external; function setReferrerTier(address _referrer, uint256 _tierId) external; function govSetCodeOwner(bytes32 _code, address _newAccount) external; }
contracts/tokens/interfaces/IWETH.sol
//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; }
contracts/access/Governable.sol
// 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; } }
contracts/core/BasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../libraries/math/SafeMath.sol"; import "../libraries/token/IERC20.sol"; import "../tokens/interfaces/IWETH.sol"; import "../libraries/token/SafeERC20.sol"; import "../libraries/utils/Address.sol"; import "../libraries/utils/ReentrancyGuard.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IShortsTracker.sol"; import "./interfaces/IOrderBook.sol"; import "./interfaces/IBasePositionManager.sol"; import "../access/Governable.sol"; import "../peripherals/interfaces/ITimelock.sol"; import "../referrals/interfaces/IReferralStorage.sol"; contract BasePositionManager is IBasePositionManager, ReentrancyGuard, Governable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address payable; uint256 public constant BASIS_POINTS_DIVISOR = 10000; address public admin; address public vault; address public shortsTracker; address public router; address public weth; // to prevent using the deposit and withdrawal of collateral as a zero fee swap, // there is a small depositFee charged if a collateral deposit results in the decrease // of leverage for an existing position // increasePositionBufferBps allows for a small amount of decrease of leverage uint256 public depositFee; uint256 public increasePositionBufferBps = 100; address public referralStorage; mapping (address => uint256) public feeReserves; mapping (address => uint256) public override maxGlobalLongSizes; mapping (address => uint256) public override maxGlobalShortSizes; event SetDepositFee(uint256 depositFee); event SetIncreasePositionBufferBps(uint256 increasePositionBufferBps); event SetReferralStorage(address referralStorage); event SetAdmin(address admin); event WithdrawFees(address token, address receiver, uint256 amount); event SetMaxGlobalSizes( address[] tokens, uint256[] longSizes, uint256[] shortSizes ); event IncreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); event DecreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); modifier onlyAdmin() { require(msg.sender == admin, "BasePositionManager: forbidden"); _; } constructor( address _vault, address _router, address _shortsTracker, address _weth, uint256 _depositFee ) public { vault = _vault; router = _router; weth = _weth; depositFee = _depositFee; shortsTracker = _shortsTracker; admin = msg.sender; } receive() external payable { require(msg.sender == weth, "BasePositionManager: invalid sender"); } function setAdmin(address _admin) external onlyGov { admin = _admin; emit SetAdmin(_admin); } function setDepositFee(uint256 _depositFee) external onlyAdmin { depositFee = _depositFee; emit SetDepositFee(_depositFee); } function setIncreasePositionBufferBps(uint256 _increasePositionBufferBps) external onlyAdmin { increasePositionBufferBps = _increasePositionBufferBps; emit SetIncreasePositionBufferBps(_increasePositionBufferBps); } function setReferralStorage(address _referralStorage) external onlyAdmin { referralStorage = _referralStorage; emit SetReferralStorage(_referralStorage); } function setMaxGlobalSizes( address[] memory _tokens, uint256[] memory _longSizes, uint256[] memory _shortSizes ) external onlyAdmin { for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; maxGlobalLongSizes[token] = _longSizes[i]; maxGlobalShortSizes[token] = _shortSizes[i]; } emit SetMaxGlobalSizes(_tokens, _longSizes, _shortSizes); } function withdrawFees(address _token, address _receiver) external onlyAdmin { uint256 amount = feeReserves[_token]; if (amount == 0) { return; } feeReserves[_token] = 0; IERC20(_token).safeTransfer(_receiver, amount); emit WithdrawFees(_token, _receiver, amount); } function approve(address _token, address _spender, uint256 _amount) external onlyGov { IERC20(_token).approve(_spender, _amount); } function sendValue(address payable _receiver, uint256 _amount) external onlyGov { _receiver.sendValue(_amount); } function _validateMaxGlobalSize(address _indexToken, bool _isLong, uint256 _sizeDelta) internal view { if (_sizeDelta == 0) { return; } if (_isLong) { uint256 maxGlobalLongSize = maxGlobalLongSizes[_indexToken]; if (maxGlobalLongSize > 0 && IVault(vault).guaranteedUsd(_indexToken).add(_sizeDelta) > maxGlobalLongSize) { revert("BasePositionManager: max global longs exceeded"); } } else { uint256 maxGlobalShortSize = maxGlobalShortSizes[_indexToken]; if (maxGlobalShortSize > 0 && IVault(vault).globalShortSizes(_indexToken).add(_sizeDelta) > maxGlobalShortSize) { revert("BasePositionManager: max global shorts exceeded"); } } } function _increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong, uint256 _price) internal { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMaxPrice(_indexToken) : IVault(_vault).getMinPrice(_indexToken); if (_isLong) { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } else { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } _validateMaxGlobalSize(_indexToken, _isLong, _sizeDelta); address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, true); ITimelock(timelock).enableLeverage(_vault); IRouter(router).pluginIncreasePosition(_account, _collateralToken, _indexToken, _sizeDelta, _isLong); ITimelock(timelock).disableLeverage(_vault); _emitIncreasePositionReferral(_account, _sizeDelta); } function _decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price) internal returns (uint256) { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMinPrice(_indexToken) : IVault(_vault).getMaxPrice(_indexToken); if (_isLong) { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } else { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, false); ITimelock(timelock).enableLeverage(_vault); uint256 amountOut = IRouter(router).pluginDecreasePosition(_account, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, _receiver); ITimelock(timelock).disableLeverage(_vault); _emitDecreasePositionReferral(_account, _sizeDelta); return amountOut; } function _emitIncreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); emit IncreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _emitDecreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); if (referralCode == bytes32(0)) { return; } emit DecreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _swap(address[] memory _path, uint256 _minOut, address _receiver) internal returns (uint256) { if (_path.length == 2) { return _vaultSwap(_path[0], _path[1], _minOut, _receiver); } revert("BasePositionManager: invalid _path.length"); } function _vaultSwap(address _tokenIn, address _tokenOut, uint256 _minOut, address _receiver) internal returns (uint256) { uint256 amountOut = IVault(vault).swap(_tokenIn, _tokenOut, _receiver); require(amountOut >= _minOut, "BasePositionManager: insufficient amountOut"); return amountOut; } function _transferInETH() internal { if (msg.value != 0) { IWETH(weth).deposit{value: msg.value}(); } } function _transferOutETHWithGasLimitIgnoreFail(uint256 _amountOut, address payable _receiver) internal { IWETH(weth).withdraw(_amountOut); // use `send` instead of `transfer` to not revert whole transaction in case ETH transfer was failed // it has limit of 2300 gas // this is to avoid front-running _receiver.send(_amountOut); } function _collectFees( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal returns (uint256) { bool shouldDeductFee = _shouldDeductFee( _account, _path, _amountIn, _indexToken, _isLong, _sizeDelta ); if (shouldDeductFee) { uint256 afterFeeAmount = _amountIn.mul(BASIS_POINTS_DIVISOR.sub(depositFee)).div(BASIS_POINTS_DIVISOR); uint256 feeAmount = _amountIn.sub(afterFeeAmount); address feeToken = _path[_path.length - 1]; feeReserves[feeToken] = feeReserves[feeToken].add(feeAmount); return afterFeeAmount; } return _amountIn; } function _shouldDeductFee( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal view returns (bool) { // if the position is a short, do not charge a fee if (!_isLong) { return false; } // if the position size is not increasing, this is a collateral deposit if (_sizeDelta == 0) { return true; } address collateralToken = _path[_path.length - 1]; IVault _vault = IVault(vault); (uint256 size, uint256 collateral, , , , , , ) = _vault.getPosition(_account, collateralToken, _indexToken, _isLong); // if there is no existing position, do not charge a fee if (size == 0) { return false; } uint256 nextSize = size.add(_sizeDelta); uint256 collateralDelta = _vault.tokenToUsdMin(collateralToken, _amountIn); uint256 nextCollateral = collateral.add(collateralDelta); uint256 prevLeverage = size.mul(BASIS_POINTS_DIVISOR).div(collateral); // allow for a maximum of a increasePositionBufferBps decrease since there might be some swap fees taken from the collateral uint256 nextLeverage = nextSize.mul(BASIS_POINTS_DIVISOR + increasePositionBufferBps).div(nextCollateral); // deduct a fee if the leverage is decreased return nextLeverage < prevLeverage; } }
contracts/core/interfaces/IOrderBook.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IOrderBook { function getSwapOrder(address _account, uint256 _orderIndex) external view returns ( address path0, address path1, address path2, uint256 amountIn, uint256 minOut, uint256 triggerRatio, bool triggerAboveThreshold, bool shouldUnwrap, uint256 executionFee ); function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns ( address purchaseToken, uint256 purchaseTokenAmount, address collateralToken, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns ( address collateralToken, uint256 collateralDelta, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function executeSwapOrder(address, uint256, address payable) external; function executeDecreaseOrder(address, uint256, address payable) external; function executeIncreaseOrder(address, uint256, address payable) external; }
contracts/core/interfaces/IRouter.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRouter { function addPlugin(address _plugin) external; function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external; function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external; function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256); function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external; }
contracts/core/interfaces/IShortsTracker.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IShortsTracker { function isGlobalShortDataReady() external view returns (bool); function globalShortAveragePrices(address _token) external view returns (uint256); function getNextGlobalShortData( address _account, address _collateralToken, address _indexToken, uint256 _nextPrice, uint256 _sizeDelta, bool _isIncrease ) external view returns (uint256, uint256); function updateGlobalShortData( address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta, uint256 _markPrice, bool _isIncrease ) external; function setIsGlobalShortDataReady(bool value) external; function setInitData(address[] calldata _tokens, uint256[] calldata _averagePrices) external; }
contracts/core/interfaces/IVault.sol
// 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 usdk() 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 getTargetUsdkAmount(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 setUsdkAmount(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 _maxUsdkAmount, 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 buyUSDK(address _token, address _receiver) external returns (uint256); function sellUSDK(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 _usdkDelta, 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 usdkAmounts(address _token) external view returns (uint256); function maxUsdkAmounts(address _token) external view returns (uint256); function getRedemptionAmount(address _token, uint256 _usdkAmount) 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); }
contracts/core/interfaces/IVaultUtils.sol
// 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 getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256); function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256); }
contracts/libraries/math/SafeMath.sol
// 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; } }
contracts/libraries/token/IERC20.sol
// 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); }
contracts/libraries/token/SafeERC20.sol
// 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"); } } }
contracts/libraries/utils/Address.sol
// 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); } } } }
contracts/libraries/utils/ReentrancyGuard.sol
// 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; } }
contracts/peripherals/interfaces/ITimelock.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ITimelock { function setAdmin(address _admin) external; function enableLeverage(address _vault) external; function disableLeverage(address _vault) external; function setIsLeverageEnabled(address _vault, bool _isLeverageEnabled) external; function signalSetGov(address _target, address _gov) external; }
contracts/core/interfaces/IBasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IBasePositionManager { function maxGlobalLongSizes(address _token) external view returns (uint256); function maxGlobalShortSizes(address _token) external view returns (uint256); }
contracts/referrals/interfaces/IReferralStorage.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IReferralStorage { function codeOwners(bytes32 _code) external view returns (address); function traderReferralCodes(address _account) external view returns (bytes32); function referrerDiscountShares(address _account) external view returns (uint256); function referrerTiers(address _account) external view returns (uint256); function getTraderReferralInfo(address _account) external view returns (bytes32, address); function setTraderReferralCode(address _account, bytes32 _code) external; function setTier(uint256 _tierId, uint256 _totalRebate, uint256 _discountShare) external; function setReferrerTier(address _referrer, uint256 _tierId) external; function govSetCodeOwner(bytes32 _code, address _newAccount) external; }
contracts/tokens/interfaces/IWETH.sol
//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; }
contracts/access/Governable.sol
// 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; } }
contracts/core/BasePositionManager.sol
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../libraries/math/SafeMath.sol"; import "../libraries/token/IERC20.sol"; import "../tokens/interfaces/IWETH.sol"; import "../libraries/token/SafeERC20.sol"; import "../libraries/utils/Address.sol"; import "../libraries/utils/ReentrancyGuard.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IShortsTracker.sol"; import "./interfaces/IOrderBook.sol"; import "./interfaces/IBasePositionManager.sol"; import "../access/Governable.sol"; import "../peripherals/interfaces/ITimelock.sol"; import "../referrals/interfaces/IReferralStorage.sol"; contract BasePositionManager is IBasePositionManager, ReentrancyGuard, Governable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address payable; uint256 public constant BASIS_POINTS_DIVISOR = 10000; address public admin; address public vault; address public shortsTracker; address public router; address public weth; // to prevent using the deposit and withdrawal of collateral as a zero fee swap, // there is a small depositFee charged if a collateral deposit results in the decrease // of leverage for an existing position // increasePositionBufferBps allows for a small amount of decrease of leverage uint256 public depositFee; uint256 public increasePositionBufferBps = 100; address public referralStorage; mapping (address => uint256) public feeReserves; mapping (address => uint256) public override maxGlobalLongSizes; mapping (address => uint256) public override maxGlobalShortSizes; event SetDepositFee(uint256 depositFee); event SetIncreasePositionBufferBps(uint256 increasePositionBufferBps); event SetReferralStorage(address referralStorage); event SetAdmin(address admin); event WithdrawFees(address token, address receiver, uint256 amount); event SetMaxGlobalSizes( address[] tokens, uint256[] longSizes, uint256[] shortSizes ); event IncreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); event DecreasePositionReferral( address account, uint256 sizeDelta, uint256 marginFeeBasisPoints, bytes32 referralCode, address referrer ); modifier onlyAdmin() { require(msg.sender == admin, "BasePositionManager: forbidden"); _; } constructor( address _vault, address _router, address _shortsTracker, address _weth, uint256 _depositFee ) public { vault = _vault; router = _router; weth = _weth; depositFee = _depositFee; shortsTracker = _shortsTracker; admin = msg.sender; } receive() external payable { require(msg.sender == weth, "BasePositionManager: invalid sender"); } function setAdmin(address _admin) external onlyGov { admin = _admin; emit SetAdmin(_admin); } function setDepositFee(uint256 _depositFee) external onlyAdmin { depositFee = _depositFee; emit SetDepositFee(_depositFee); } function setIncreasePositionBufferBps(uint256 _increasePositionBufferBps) external onlyAdmin { increasePositionBufferBps = _increasePositionBufferBps; emit SetIncreasePositionBufferBps(_increasePositionBufferBps); } function setReferralStorage(address _referralStorage) external onlyAdmin { referralStorage = _referralStorage; emit SetReferralStorage(_referralStorage); } function setMaxGlobalSizes( address[] memory _tokens, uint256[] memory _longSizes, uint256[] memory _shortSizes ) external onlyAdmin { for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; maxGlobalLongSizes[token] = _longSizes[i]; maxGlobalShortSizes[token] = _shortSizes[i]; } emit SetMaxGlobalSizes(_tokens, _longSizes, _shortSizes); } function withdrawFees(address _token, address _receiver) external onlyAdmin { uint256 amount = feeReserves[_token]; if (amount == 0) { return; } feeReserves[_token] = 0; IERC20(_token).safeTransfer(_receiver, amount); emit WithdrawFees(_token, _receiver, amount); } function approve(address _token, address _spender, uint256 _amount) external onlyGov { IERC20(_token).approve(_spender, _amount); } function sendValue(address payable _receiver, uint256 _amount) external onlyGov { _receiver.sendValue(_amount); } function _validateMaxGlobalSize(address _indexToken, bool _isLong, uint256 _sizeDelta) internal view { if (_sizeDelta == 0) { return; } if (_isLong) { uint256 maxGlobalLongSize = maxGlobalLongSizes[_indexToken]; if (maxGlobalLongSize > 0 && IVault(vault).guaranteedUsd(_indexToken).add(_sizeDelta) > maxGlobalLongSize) { revert("BasePositionManager: max global longs exceeded"); } } else { uint256 maxGlobalShortSize = maxGlobalShortSizes[_indexToken]; if (maxGlobalShortSize > 0 && IVault(vault).globalShortSizes(_indexToken).add(_sizeDelta) > maxGlobalShortSize) { revert("BasePositionManager: max global shorts exceeded"); } } } function _increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong, uint256 _price) internal { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMaxPrice(_indexToken) : IVault(_vault).getMinPrice(_indexToken); if (_isLong) { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } else { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } _validateMaxGlobalSize(_indexToken, _isLong, _sizeDelta); address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, true); ITimelock(timelock).enableLeverage(_vault); IRouter(router).pluginIncreasePosition(_account, _collateralToken, _indexToken, _sizeDelta, _isLong); ITimelock(timelock).disableLeverage(_vault); _emitIncreasePositionReferral(_account, _sizeDelta); } function _decreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver, uint256 _price) internal returns (uint256) { address _vault = vault; uint256 markPrice = _isLong ? IVault(_vault).getMinPrice(_indexToken) : IVault(_vault).getMaxPrice(_indexToken); if (_isLong) { require(markPrice >= _price, "BasePositionManager: mark price lower than limit"); } else { require(markPrice <= _price, "BasePositionManager: mark price higher than limit"); } address timelock = IVault(_vault).gov(); // should be called strictly before position is updated in Vault IShortsTracker(shortsTracker).updateGlobalShortData(_account, _collateralToken, _indexToken, _isLong, _sizeDelta, markPrice, false); ITimelock(timelock).enableLeverage(_vault); uint256 amountOut = IRouter(router).pluginDecreasePosition(_account, _collateralToken, _indexToken, _collateralDelta, _sizeDelta, _isLong, _receiver); ITimelock(timelock).disableLeverage(_vault); _emitDecreasePositionReferral(_account, _sizeDelta); return amountOut; } function _emitIncreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); emit IncreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _emitDecreasePositionReferral(address _account, uint256 _sizeDelta) internal { address _referralStorage = referralStorage; if (_referralStorage == address(0)) { return; } (bytes32 referralCode, address referrer) = IReferralStorage(_referralStorage).getTraderReferralInfo(_account); if (referralCode == bytes32(0)) { return; } emit DecreasePositionReferral( _account, _sizeDelta, IVault(vault).marginFeeBasisPoints(), referralCode, referrer ); } function _swap(address[] memory _path, uint256 _minOut, address _receiver) internal returns (uint256) { if (_path.length == 2) { return _vaultSwap(_path[0], _path[1], _minOut, _receiver); } revert("BasePositionManager: invalid _path.length"); } function _vaultSwap(address _tokenIn, address _tokenOut, uint256 _minOut, address _receiver) internal returns (uint256) { uint256 amountOut = IVault(vault).swap(_tokenIn, _tokenOut, _receiver); require(amountOut >= _minOut, "BasePositionManager: insufficient amountOut"); return amountOut; } function _transferInETH() internal { if (msg.value != 0) { IWETH(weth).deposit{value: msg.value}(); } } function _transferOutETHWithGasLimitIgnoreFail(uint256 _amountOut, address payable _receiver) internal { IWETH(weth).withdraw(_amountOut); // use `send` instead of `transfer` to not revert whole transaction in case ETH transfer was failed // it has limit of 2300 gas // this is to avoid front-running _receiver.send(_amountOut); } function _collectFees( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal returns (uint256) { bool shouldDeductFee = _shouldDeductFee( _account, _path, _amountIn, _indexToken, _isLong, _sizeDelta ); if (shouldDeductFee) { uint256 afterFeeAmount = _amountIn.mul(BASIS_POINTS_DIVISOR.sub(depositFee)).div(BASIS_POINTS_DIVISOR); uint256 feeAmount = _amountIn.sub(afterFeeAmount); address feeToken = _path[_path.length - 1]; feeReserves[feeToken] = feeReserves[feeToken].add(feeAmount); return afterFeeAmount; } return _amountIn; } function _shouldDeductFee( address _account, address[] memory _path, uint256 _amountIn, address _indexToken, bool _isLong, uint256 _sizeDelta ) internal view returns (bool) { // if the position is a short, do not charge a fee if (!_isLong) { return false; } // if the position size is not increasing, this is a collateral deposit if (_sizeDelta == 0) { return true; } address collateralToken = _path[_path.length - 1]; IVault _vault = IVault(vault); (uint256 size, uint256 collateral, , , , , , ) = _vault.getPosition(_account, collateralToken, _indexToken, _isLong); // if there is no existing position, do not charge a fee if (size == 0) { return false; } uint256 nextSize = size.add(_sizeDelta); uint256 collateralDelta = _vault.tokenToUsdMin(collateralToken, _amountIn); uint256 nextCollateral = collateral.add(collateralDelta); uint256 prevLeverage = size.mul(BASIS_POINTS_DIVISOR).div(collateral); // allow for a maximum of a increasePositionBufferBps decrease since there might be some swap fees taken from the collateral uint256 nextLeverage = nextSize.mul(BASIS_POINTS_DIVISOR + increasePositionBufferBps).div(nextCollateral); // deduct a fee if the leverage is decreased return nextLeverage < prevLeverage; } }
contracts/core/interfaces/IOrderBook.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IOrderBook { function getSwapOrder(address _account, uint256 _orderIndex) external view returns ( address path0, address path1, address path2, uint256 amountIn, uint256 minOut, uint256 triggerRatio, bool triggerAboveThreshold, bool shouldUnwrap, uint256 executionFee ); function getIncreaseOrder(address _account, uint256 _orderIndex) external view returns ( address purchaseToken, uint256 purchaseTokenAmount, address collateralToken, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function getDecreaseOrder(address _account, uint256 _orderIndex) external view returns ( address collateralToken, uint256 collateralDelta, address indexToken, uint256 sizeDelta, bool isLong, uint256 triggerPrice, bool triggerAboveThreshold, uint256 executionFee ); function executeSwapOrder(address, uint256, address payable) external; function executeDecreaseOrder(address, uint256, address payable) external; function executeIncreaseOrder(address, uint256, address payable) external; }
contracts/core/interfaces/IRouter.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRouter { function addPlugin(address _plugin) external; function pluginTransfer(address _token, address _account, address _receiver, uint256 _amount) external; function pluginIncreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external; function pluginDecreasePosition(address _account, address _collateralToken, address _indexToken, uint256 _collateralDelta, uint256 _sizeDelta, bool _isLong, address _receiver) external returns (uint256); function swap(address[] memory _path, uint256 _amountIn, uint256 _minOut, address _receiver) external; }
contracts/core/interfaces/IShortsTracker.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IShortsTracker { function isGlobalShortDataReady() external view returns (bool); function globalShortAveragePrices(address _token) external view returns (uint256); function getNextGlobalShortData( address _account, address _collateralToken, address _indexToken, uint256 _nextPrice, uint256 _sizeDelta, bool _isIncrease ) external view returns (uint256, uint256); function updateGlobalShortData( address _account, address _collateralToken, address _indexToken, bool _isLong, uint256 _sizeDelta, uint256 _markPrice, bool _isIncrease ) external; function setIsGlobalShortDataReady(bool value) external; function setInitData(address[] calldata _tokens, uint256[] calldata _averagePrices) external; }
contracts/core/interfaces/IVault.sol
// 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 usdk() 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 getTargetUsdkAmount(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 setUsdkAmount(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 _maxUsdkAmount, 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 buyUSDK(address _token, address _receiver) external returns (uint256); function sellUSDK(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 _usdkDelta, 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 usdkAmounts(address _token) external view returns (uint256); function maxUsdkAmounts(address _token) external view returns (uint256); function getRedemptionAmount(address _token, uint256 _usdkAmount) 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); }
contracts/core/interfaces/IVaultUtils.sol
// 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 getBuyUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSellUsdkFeeBasisPoints(address _token, uint256 _usdkAmount) external view returns (uint256); function getSwapFeeBasisPoints(address _tokenIn, address _tokenOut, uint256 _usdkAmount) external view returns (uint256); function getFeeBasisPoints(address _token, uint256 _usdkDelta, uint256 _feeBasisPoints, uint256 _taxBasisPoints, bool _increment) external view returns (uint256); }
contracts/libraries/math/SafeMath.sol
// 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; } }
contracts/libraries/token/IERC20.sol
// 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); }
contracts/libraries/token/SafeERC20.sol
// 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"); } } }
contracts/libraries/utils/Address.sol
// 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); } } } }
contracts/libraries/utils/ReentrancyGuard.sol
// 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; } }
contracts/peripherals/interfaces/ITimelock.sol
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ITimelock { function setAdmin(address _admin) external; function enableLeverage(address _vault) external; function disableLeverage(address _vault) external; function setIsLeverageEnabled(address _vault, bool _isLeverageEnabled) external; function signalSetGov(address _target, address _gov) external; }
Contract ABI
[{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address","name":"_vault","internalType":"address"},{"type":"address","name":"_router","internalType":"address"},{"type":"address","name":"_shortsTracker","internalType":"address"},{"type":"address","name":"_weth","internalType":"address"},{"type":"uint256","name":"_depositFee","internalType":"uint256"},{"type":"address","name":"_orderBook","internalType":"address"}]},{"type":"event","name":"DecreasePositionReferral","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"uint256","name":"marginFeeBasisPoints","internalType":"uint256","indexed":false},{"type":"bytes32","name":"referralCode","internalType":"bytes32","indexed":false},{"type":"address","name":"referrer","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"IncreasePositionReferral","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"uint256","name":"sizeDelta","internalType":"uint256","indexed":false},{"type":"uint256","name":"marginFeeBasisPoints","internalType":"uint256","indexed":false},{"type":"bytes32","name":"referralCode","internalType":"bytes32","indexed":false},{"type":"address","name":"referrer","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"SetAdmin","inputs":[{"type":"address","name":"admin","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"SetDepositFee","inputs":[{"type":"uint256","name":"depositFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"SetInLegacyMode","inputs":[{"type":"bool","name":"inLegacyMode","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"SetIncreasePositionBufferBps","inputs":[{"type":"uint256","name":"increasePositionBufferBps","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"SetLiquidator","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"bool","name":"isActive","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"SetMaxGlobalSizes","inputs":[{"type":"address[]","name":"tokens","internalType":"address[]","indexed":false},{"type":"uint256[]","name":"longSizes","internalType":"uint256[]","indexed":false},{"type":"uint256[]","name":"shortSizes","internalType":"uint256[]","indexed":false}],"anonymous":false},{"type":"event","name":"SetOrderKeeper","inputs":[{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"bool","name":"isActive","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"SetPartner","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"bool","name":"isActive","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"SetReferralStorage","inputs":[{"type":"address","name":"referralStorage","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"SetShouldValidateIncreaseOrder","inputs":[{"type":"bool","name":"shouldValidateIncreaseOrder","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"WithdrawFees","inputs":[{"type":"address","name":"token","internalType":"address","indexed":false},{"type":"address","name":"receiver","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"BASIS_POINTS_DIVISOR","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"admin","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"approve","inputs":[{"type":"address","name":"_token","internalType":"address"},{"type":"address","name":"_spender","internalType":"address"},{"type":"uint256","name":"_amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"decreasePosition","inputs":[{"type":"address","name":"_collateralToken","internalType":"address"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_collateralDelta","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"address","name":"_receiver","internalType":"address"},{"type":"uint256","name":"_price","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"decreasePositionAndSwap","inputs":[{"type":"address[]","name":"_path","internalType":"address[]"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_collateralDelta","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"address","name":"_receiver","internalType":"address"},{"type":"uint256","name":"_price","internalType":"uint256"},{"type":"uint256","name":"_minOut","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"decreasePositionAndSwapETH","inputs":[{"type":"address[]","name":"_path","internalType":"address[]"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_collateralDelta","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"address","name":"_receiver","internalType":"address payable"},{"type":"uint256","name":"_price","internalType":"uint256"},{"type":"uint256","name":"_minOut","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"decreasePositionETH","inputs":[{"type":"address","name":"_collateralToken","internalType":"address"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_collateralDelta","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"address","name":"_receiver","internalType":"address payable"},{"type":"uint256","name":"_price","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"depositFee","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeDecreaseOrder","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"address","name":"_feeReceiver","internalType":"address payable"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeIncreaseOrder","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"address","name":"_feeReceiver","internalType":"address payable"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"executeSwapOrder","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"uint256","name":"_orderIndex","internalType":"uint256"},{"type":"address","name":"_feeReceiver","internalType":"address payable"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"feeReserves","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"gov","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"inLegacyMode","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"increasePosition","inputs":[{"type":"address[]","name":"_path","internalType":"address[]"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_amountIn","internalType":"uint256"},{"type":"uint256","name":"_minOut","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"uint256","name":"_price","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"increasePositionBufferBps","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"increasePositionETH","inputs":[{"type":"address[]","name":"_path","internalType":"address[]"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"uint256","name":"_minOut","internalType":"uint256"},{"type":"uint256","name":"_sizeDelta","internalType":"uint256"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"uint256","name":"_price","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isLiquidator","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isOrderKeeper","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isPartner","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"liquidatePosition","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"address","name":"_collateralToken","internalType":"address"},{"type":"address","name":"_indexToken","internalType":"address"},{"type":"bool","name":"_isLong","internalType":"bool"},{"type":"address","name":"_feeReceiver","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"maxGlobalLongSizes","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"maxGlobalShortSizes","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"orderBook","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"referralStorage","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"router","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"sendValue","inputs":[{"type":"address","name":"_receiver","internalType":"address payable"},{"type":"uint256","name":"_amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setAdmin","inputs":[{"type":"address","name":"_admin","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setDepositFee","inputs":[{"type":"uint256","name":"_depositFee","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setGov","inputs":[{"type":"address","name":"_gov","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setInLegacyMode","inputs":[{"type":"bool","name":"_inLegacyMode","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setIncreasePositionBufferBps","inputs":[{"type":"uint256","name":"_increasePositionBufferBps","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setLiquidator","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"bool","name":"_isActive","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setMaxGlobalSizes","inputs":[{"type":"address[]","name":"_tokens","internalType":"address[]"},{"type":"uint256[]","name":"_longSizes","internalType":"uint256[]"},{"type":"uint256[]","name":"_shortSizes","internalType":"uint256[]"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setOrderKeeper","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"bool","name":"_isActive","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setPartner","inputs":[{"type":"address","name":"_account","internalType":"address"},{"type":"bool","name":"_isActive","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setReferralStorage","inputs":[{"type":"address","name":"_referralStorage","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setShouldValidateIncreaseOrder","inputs":[{"type":"bool","name":"_shouldValidateIncreaseOrder","internalType":"bool"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"shortsTracker","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"shouldValidateIncreaseOrder","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"vault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"weth","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"withdrawFees","inputs":[{"type":"address","name":"_token","internalType":"address"},{"type":"address","name":"_receiver","internalType":"address"}]},{"type":"receive","stateMutability":"payable"}]
Contract Creation Code
0x60806040526064600855600d805460ff60a81b1916600160a81b17905534801561002857600080fd5b506040516200513938038062005139833981810160405260c081101561004d57600080fd5b508051602082015160408301516060840151608085015160a0909501516001600081905580546001600160a01b031990811633908117909255600380546001600160a01b039889169083161790556005805496881696821696909617909555600680549387169386169390931790925560079590955560048054928516928416929092179091556002805483169091179055600d805492909316911617905561503d80620000fc6000396000f3fe6080604052600436106101ff5760003560e01c8063657bc5d011610114578063657bc5d0146107da57806367a52793146107ef578063704b6c0214610804578063776af5ba146108375780638c0f9aac1461084c57806390205d8c1461087f5780639698d25a146108de57806398d1e03a146109115780639c95332f14610926578063ae4d7f9a14610952578063b32755de14610985578063b7ddc99214610a48578063cfad57a214610b1e578063d38ab51914610b51578063d4ca83f914610b94578063de2ea94814610ba9578063e1f21c6714610bfe578063ef12c67e14610c41578063f255527814610df3578063f851a44014610e2e578063f887ea4014610e43578063fbfa77cf14610e585761024f565b80626cc35e1461025457806307c7edc3146102855780631045c74e146102c857806311d9444a1461030d578063126082cf1461035057806312d43a51146103655780631b9043591461037a5780631ce9cb8f146103a65780631e261538146103d957806321acf65914610414578063233bfe3b1461044f57806324a084df146104795780633039e37f146104b25780633833f5f5146105925780633fc8cef3146105d9578063430ed37c146105ee5780634453a3741461064d5780634584bd4b14610688578063490ae2101461069d578063529a356f146106c75780635fc8500e146106fa5761024f565b3661024f576006546001600160a01b0316331461024d5760405162461bcd60e51b8152600401808060200182810382526023815260200180614f966023913960400191505060405180910390fd5b005b600080fd5b34801561026057600080fd5b50610269610e6d565b604080516001600160a01b039092168252519081900360200190f35b34801561029157600080fd5b5061024d600480360360608110156102a857600080fd5b506001600160a01b03813581169160208101359160409091013516610e7c565b3480156102d457600080fd5b506102fb600480360360208110156102eb57600080fd5b50356001600160a01b0316610f48565b60408051918252519081900360200190f35b34801561031957600080fd5b5061024d6004803603606081101561033057600080fd5b506001600160a01b03813581169160208101359160409091013516610f5a565b34801561035c57600080fd5b506102fb6113ba565b34801561037157600080fd5b506102696113c0565b34801561038657600080fd5b5061024d6004803603602081101561039d57600080fd5b503515156113cf565b3480156103b257600080fd5b506102fb600480360360208110156103c957600080fd5b50356001600160a01b031661146f565b3480156103e557600080fd5b5061024d600480360360408110156103fc57600080fd5b506001600160a01b0381351690602001351515611481565b34801561042057600080fd5b5061024d6004803603604081101561043757600080fd5b506001600160a01b038135169060200135151561152e565b34801561045b57600080fd5b5061024d6004803603602081101561047257600080fd5b50356115df565b34801561048557600080fd5b5061024d6004803603604081101561049c57600080fd5b506001600160a01b038135169060200135611667565b3480156104be57600080fd5b5061024d60048036036101008110156104d657600080fd5b810190602081018135600160201b8111156104f057600080fd5b82018360208201111561050257600080fd5b803590602001918460208302840111600160201b8311171561052357600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505081356001600160a01b0390811693506020830135926040810135925060608101351515916080820135169060a08101359060c001356116cb565b34801561059e57600080fd5b506105c5600480360360208110156105b557600080fd5b50356001600160a01b03166118d8565b604080519115158252519081900360200190f35b3480156105e557600080fd5b506102696118ed565b3480156105fa57600080fd5b5061024d600480360360e081101561061157600080fd5b506001600160a01b0381358116916020810135821691604082013591606081013591608082013515159160a08101359091169060c001356118fc565b34801561065957600080fd5b5061024d6004803603604081101561067057600080fd5b506001600160a01b0381351690602001351515611a25565b34801561069457600080fd5b506105c5611ad2565b3480156106a957600080fd5b5061024d600480360360208110156106c057600080fd5b5035611ae2565b3480156106d357600080fd5b506105c5600480360360208110156106ea57600080fd5b50356001600160a01b0316611b6a565b34801561070657600080fd5b5061024d600480360361010081101561071e57600080fd5b810190602081018135600160201b81111561073857600080fd5b82018360208201111561074a57600080fd5b803590602001918460208302840111600160201b8311171561076b57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505081356001600160a01b0390811693506020830135926040810135925060608101351515916080820135169060a08101359060c00135611b7f565b3480156107e657600080fd5b50610269611cb6565b3480156107fb57600080fd5b506102fb611cc5565b34801561081057600080fd5b5061024d6004803603602081101561082757600080fd5b50356001600160a01b0316611ccb565b34801561084357600080fd5b50610269611d6c565b34801561085857600080fd5b506105c56004803603602081101561086f57600080fd5b50356001600160a01b0316611d7b565b34801561088b57600080fd5b5061024d600480360360e08110156108a257600080fd5b506001600160a01b0381358116916020810135821691604082013591606081013591608082013515159160a08101359091169060c00135611d90565b3480156108ea57600080fd5b506102fb6004803603602081101561090157600080fd5b50356001600160a01b0316611e50565b34801561091d57600080fd5b506102fb611e62565b34801561093257600080fd5b5061024d6004803603602081101561094957600080fd5b50351515611e68565b34801561095e57600080fd5b5061024d6004803603602081101561097557600080fd5b50356001600160a01b0316611f08565b61024d600480360360c081101561099b57600080fd5b810190602081018135600160201b8111156109b557600080fd5b8201836020820111156109c757600080fd5b803590602001918460208302840111600160201b831117156109e857600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550506001600160a01b0383351693505050602081013590604081013590606081013515159060800135611fa9565b348015610a5457600080fd5b5061024d600480360360e0811015610a6b57600080fd5b810190602081018135600160201b811115610a8557600080fd5b820183602082011115610a9757600080fd5b803590602001918460208302840111600160201b83111715610ab857600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550506001600160a01b0383351693505050602081013590604081013590606081013590608081013515159060a001356121da565b348015610b2a57600080fd5b5061024d60048036036020811015610b4157600080fd5b50356001600160a01b03166124b9565b348015610b5d57600080fd5b5061024d60048036036060811015610b7457600080fd5b506001600160a01b03813581169160208101359160409091013516612528565b348015610ba057600080fd5b506105c5612989565b348015610bb557600080fd5b5061024d600480360360a0811015610bcc57600080fd5b506001600160a01b03813581169160208101358216916040820135811691606081013515159160809091013516612999565b348015610c0a57600080fd5b5061024d60048036036060811015610c2157600080fd5b506001600160a01b03813581169160208101359091169060400135612e3e565b348015610c4d57600080fd5b5061024d60048036036060811015610c6457600080fd5b810190602081018135600160201b811115610c7e57600080fd5b820183602082011115610c9057600080fd5b803590602001918460208302840111600160201b83111715610cb157600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610d0057600080fd5b820183602082011115610d1257600080fd5b803590602001918460208302840111600160201b83111715610d3357600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610d8257600080fd5b820183602082011115610d9457600080fd5b803590602001918460208302840111600160201b83111715610db557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612f13945050505050565b348015610dff57600080fd5b5061024d60048036036040811015610e1657600080fd5b506001600160a01b0381358116916020013516613102565b348015610e3a57600080fd5b506102696131e6565b348015610e4f57600080fd5b506102696131f5565b348015610e6457600080fd5b50610269613204565b6009546001600160a01b031681565b336000908152600e602052604090205460ff16610ece576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b600d54604080516307c7edc360e01b81526001600160a01b038681166004830152602482018690528481166044830152915191909216916307c7edc391606480830192600092919082900301818387803b158015610f2b57600080fd5b505af1158015610f3f573d6000803e3d6000fd5b50505050505050565b600b6020526000908152604090205481565b336000908152600e602052604090205460ff16610fac576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b600354604080516312d43a5160e01b815290516001600160a01b039092169160009183916312d43a5191600480820192602092909190829003018186803b158015610ff657600080fd5b505afa15801561100a573d6000803e3d6000fd5b505050506040513d602081101561102057600080fd5b5051600d5460408051630130197760e11b81526001600160a01b03898116600483015260248201899052915193945060009384938493849391169163026032ee9160448082019261010092909190829003018186803b15801561108257600080fd5b505afa158015611096573d6000803e3d6000fd5b505050506040513d6101008110156110ad57600080fd5b508051604082015160608301516080909301519196509450909250905060008161114f57866001600160a01b031663e124e6d2856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561111e57600080fd5b505afa158015611132573d6000803e3d6000fd5b505050506040513d602081101561114857600080fd5b50516111c9565b866001600160a01b03166381a612d6856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561119c57600080fd5b505afa1580156111b0573d6000803e3d6000fd5b505050506040513d60208110156111c657600080fd5b50515b6004805460408051633cc8e33b60e21b81526001600160a01b038f8116948201949094528984166024820152888416604482015286151560648201526084810188905260a48101859052600060c482018190529151949550929091169263f3238cec9260e480820193929182900301818387803b15801561124957600080fd5b505af115801561125d573d6000803e3d6000fd5b50505050856001600160a01b0316636d63c1d0886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b1580156112b057600080fd5b505af11580156112c4573d6000803e3d6000fd5b5050600d54604080516308eca22560e11b81526001600160a01b038f81166004830152602482018f90528d8116604483015291519190921693506311d9444a9250606480830192600092919082900301818387803b15801561132557600080fd5b505af1158015611339573d6000803e3d6000fd5b50505050856001600160a01b031663d3c87bbb886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b15801561138c57600080fd5b505af11580156113a0573d6000803e3d6000fd5b505050506113ae8a84613213565b50505050505050505050565b61271081565b6001546001600160a01b031681565b6002546001600160a01b0316331461141c576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b600d8054821515600160a81b810260ff60a81b199092169190911790915560408051918252517fa956222e37fe025ff51e5440ac729a9bd417ff91e485e14dcffa2c0ba8894f409181900360200190a150565b600a6020526000908152604090205481565b6002546001600160a01b031633146114ce576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b0382166000818152600e6020908152604091829020805460ff1916851515908117909155825190815291517f1d5bc0255b943d6a5b5279e8a55d74d620baccbceecb25e87a3558f14c4c118e9281900390910190a25050565b6002546001600160a01b0316331461157b576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b0382166000818152600f6020908152604091829020805460ff191685151590811790915582519384529083015280517fa4e46c70ff429a91de7d1716d736e877c7cca1c22ac850b23d242530dd95e4749281900390910190a15050565b6002546001600160a01b0316331461162c576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b60088190556040805182815290517f21167d0d4661af93817ebce920f18986eed3d75d5e1c03f2aed05efcbafbc4529181900360200190a150565b6001546001600160a01b031633146116b4576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b6116c76001600160a01b0383168261339c565b5050565b60026000541415611711576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061173c5750600d54600160a01b900460ff165b61177b576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b87516002146117bb5760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b60065488516001600160a01b0390911690899060001981019081106117dc57fe5b60200260200101516001600160a01b03161461183f576040805162461bcd60e51b815260206004820152601e60248201527f506f736974696f6e4d616e616765723a20696e76616c6964205f706174680000604482015290519081900360640190fd5b6000611865338a60008151811061185257fe5b60200260200101518a8a8a8a308a613486565b90506118ae600360009054906101000a90046001600160a01b0316828b60008151811061188e57fe5b60200260200101516001600160a01b031661391f9092919063ffffffff16565b60006118bb8a8430613971565b90506118c781866139f6565b505060016000555050505050505050565b600e6020526000908152604090205460ff1681565b6006546001600160a01b031681565b60026000541415611942576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061196d5750600d54600160a01b900460ff165b6119ac576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b6006546001600160a01b038881169116146119f85760405162461bcd60e51b8152600401808060200182810382526029815260200180614f6d6029913960400191505060405180910390fd5b6000611a0a3389898989893089613486565b9050611a1681846139f6565b50506001600055505050505050565b6002546001600160a01b03163314611a72576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b038216600081815260106020908152604091829020805460ff1916851515908117909155825190815291517f8c0d56805c3b43d441481229dc64bee168253ffe4305f37ab7cfe63b1c4268c69281900390910190a25050565b600d54600160a81b900460ff1681565b6002546001600160a01b03163314611b2f576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b60078190556040805182815290517f974fd3c1fcb4653dfc4fb740c4c692cd212d55c28f163f310128cb64d83006759181900360200190a150565b60106020526000908152604090205460ff1681565b60026000541415611bc5576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff1680611bf05750600d54600160a01b900460ff165b611c2f576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b8751600214611c6f5760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b6000611c82338a60008151811061185257fe5b9050611cab600360009054906101000a90046001600160a01b0316828b60008151811061188e57fe5b6118c7898386613971565b6004546001600160a01b031681565b60075481565b6001546001600160a01b03163314611d18576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b600280546001600160a01b0383166001600160a01b0319909116811790915560408051918252517f5a272403b402d892977df56625f4164ccaf70ca3863991c43ecfe76a6905b0a19181900360200190a150565b600d546001600160a01b031681565b600f6020526000908152604090205460ff1681565b60026000541415611dd6576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff1680611e015750600d54600160a01b900460ff165b611e40576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b611a163388888888888888613486565b600c6020526000908152604090205481565b60085481565b6002546001600160a01b03163314611eb5576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b600d8054821515600160a01b810260ff60a01b199092169190911790915560408051918252517feac6b3611e79ff0d8ea5daa8439f6b1ab7eea4ebf95f1dd360417f712c3fc3049181900360200190a150565b6002546001600160a01b03163314611f55576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b600980546001600160a01b0383166001600160a01b0319909116811790915560408051918252517f828abcccea18192c21d645e575652c49e20b986dab777906fc473d056b01b6a89181900360200190a150565b60026000541415611fef576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061201a5750600d54600160a01b900460ff165b612059576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b85516001148061206a575085516002145b6120a55760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b60065486516001600160a01b039091169087906000906120c157fe5b60200260200101516001600160a01b031614612124576040805162461bcd60e51b815260206004820152601e60248201527f506f736974696f6e4d616e616765723a20696e76616c6964205f706174680000604482015290519081900360640190fd5b34156121a857612132613a84565b85513490600110156121695760035460065461215b916001600160a01b0391821691163461391f565b612166878630613971565b90505b60006121793389848a888a613af0565b90506121a5600360009054906101000a90046001600160a01b0316828a60018c51038151811061188e57fe5b50505b6121cd33876001895103815181106121bc57fe5b602002602001015187868686613bcf565b5050600160005550505050565b60026000541415612220576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061224b5750600d54600160a01b900460ff165b61228a576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b86516001148061229b575086516002145b6122d65760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b8415612486578651600114156123965760055487516001600160a01b0390911690631b82787890899060009061230857fe5b60200260200101513330896040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846001600160a01b03168152602001836001600160a01b03168152602001828152602001945050505050600060405180830381600087803b15801561237957600080fd5b505af115801561238d573d6000803e3d6000fd5b50505050612448565b60055487516001600160a01b0390911690631b8278789089906000906123b857fe5b6020908102919091010151600354604080516001600160e01b031960e086901b1681526001600160a01b0393841660048201523360248201529290911660448301526064820189905251608480830192600092919082900301818387803b15801561242257600080fd5b505af1158015612436573d6000803e3d6000fd5b50505050612445878530613971565b94505b60006124583389888a8789613af0565b9050612484600360009054906101000a90046001600160a01b0316828a60018c51038151811061188e57fe5b505b6124ab338860018a51038151811061249a57fe5b602002602001015188868686613bcf565b505060016000555050505050565b6001546001600160a01b03163314612506576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b336000908152600e602052604090205460ff1661257a576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b6125848383613fd7565b600354604080516312d43a5160e01b815290516001600160a01b039092169160009183916312d43a5191600480820192602092909190829003018186803b1580156125ce57600080fd5b505afa1580156125e2573d6000803e3d6000fd5b505050506040513d60208110156125f857600080fd5b5051600d546040805163d3bab1d160e01b81526001600160a01b03898116600483015260248201899052915193945060009384938493849391169163d3bab1d19160448082019261012092909190829003018186803b15801561265a57600080fd5b505afa15801561266e573d6000803e3d6000fd5b505050506040513d61012081101561268557600080fd5b5060408101516060820151608083015160a0909301519196509450909250905060008161272a57866001600160a01b03166381a612d6856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156126f957600080fd5b505afa15801561270d573d6000803e3d6000fd5b505050506040513d602081101561272357600080fd5b50516127a4565b866001600160a01b031663e124e6d2856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561277757600080fd5b505afa15801561278b573d6000803e3d6000fd5b505050506040513d60208110156127a157600080fd5b50515b6004805460408051633cc8e33b60e21b81526001600160a01b038f8116948201949094528984166024820152888416604482015286151560648201526084810188905260a48101859052600160c4820152905193945091169163f3238cec9160e48082019260009290919082900301818387803b15801561282457600080fd5b505af1158015612838573d6000803e3d6000fd5b50505050856001600160a01b0316636d63c1d0886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b15801561288b57600080fd5b505af115801561289f573d6000803e3d6000fd5b5050600d546040805163d38ab51960e01b81526001600160a01b038f81166004830152602482018f90528d81166044830152915191909216935063d38ab5199250606480830192600092919082900301818387803b15801561290057600080fd5b505af1158015612914573d6000803e3d6000fd5b50505050856001600160a01b031663d3c87bbb886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b15801561296757600080fd5b505af115801561297b573d6000803e3d6000fd5b505050506113ae8a846142fa565b600d54600160a01b900460ff1681565b600260005414156129df576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b600260009081553381526010602052604090205460ff16612a35576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b600354604080516312d43a5160e01b815290516001600160a01b039092169160009183916312d43a5191600480820192602092909190829003018186803b158015612a7f57600080fd5b505afa158015612a93573d6000803e3d6000fd5b505050506040513d6020811015612aa957600080fd5b505160035460408051634a3f088d60e01b81526001600160a01b038b811660048301528a811660248301528981166044830152881515606483015291519394506000939190921691634a3f088d91608480830192610100929190829003018186803b158015612b1757600080fd5b505afa158015612b2b573d6000803e3d6000fd5b505050506040513d610100811015612b4257600080fd5b50519050600085612bcb57836001600160a01b031663e124e6d2886040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015612b9a57600080fd5b505afa158015612bae573d6000803e3d6000fd5b505050506040513d6020811015612bc457600080fd5b5051612c45565b836001600160a01b03166381a612d6886040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015612c1857600080fd5b505afa158015612c2c573d6000803e3d6000fd5b505050506040513d6020811015612c4257600080fd5b50515b6004805460408051633cc8e33b60e21b81526001600160a01b038e8116948201949094528c841660248201528b841660448201528a151560648201526084810187905260a48101859052600060c482018190529151949550929091169263f3238cec9260e480820193929182900301818387803b158015612cc557600080fd5b505af1158015612cd9573d6000803e3d6000fd5b50505050826001600160a01b0316636d63c1d0856040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015612d2c57600080fd5b505af1158015612d40573d6000803e3d6000fd5b505060408051631bc5d52960e31b81526001600160a01b038d811660048301528c811660248301528b811660448301528a1515606483015289811660848301529151918816935063de2ea948925060a48082019260009290919082900301818387803b158015612daf57600080fd5b505af1158015612dc3573d6000803e3d6000fd5b50505050826001600160a01b031663d3c87bbb856040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015612e1657600080fd5b505af1158015612e2a573d6000803e3d6000fd5b505060016000555050505050505050505050565b6001546001600160a01b03163314612e8b576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b826001600160a01b031663095ea7b383836040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050602060405180830381600087803b158015612ee257600080fd5b505af1158015612ef6573d6000803e3d6000fd5b505050506040513d6020811015612f0c57600080fd5b5050505050565b6002546001600160a01b03163314612f60576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b60005b8351811015612ffb576000848281518110612f7a57fe5b60200260200101519050838281518110612f9057fe5b6020026020010151600b6000836001600160a01b03166001600160a01b0316815260200190815260200160002081905550828281518110612fcd57fe5b6020908102919091018101516001600160a01b039092166000908152600c9091526040902055600101612f63565b507fae32d569b058895b9620d6552b09aaffedc9a6f396be4d595a224ad09f8b213983838360405180806020018060200180602001848103845287818151815260200191508051906020019060200280838360005b83811015613068578181015183820152602001613050565b50505050905001848103835286818151815260200191508051906020019060200280838360005b838110156130a757818101518382015260200161308f565b50505050905001848103825285818151815260200191508051906020019060200280838360005b838110156130e65781810151838201526020016130ce565b50505050905001965050505050505060405180910390a1505050565b6002546001600160a01b0316331461314f576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b0382166000908152600a60205260409020548061317357506116c7565b6001600160a01b0383166000818152600a602052604081205561319790838361391f565b604080516001600160a01b0380861682528416602082015280820183905290517f4f1b51dd7a2fcb861aa2670f668be66835c4ee12b4bbbf037e4d0018f39819e49181900360600190a1505050565b6002546001600160a01b031681565b6005546001600160a01b031681565b6003546001600160a01b031681565b6009546001600160a01b03168061322a57506116c7565b600080826001600160a01b031663534ef883866040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050604080518083038186803b15801561327957600080fd5b505afa15801561328d573d6000803e3d6000fd5b505050506040513d60408110156132a357600080fd5b5080516020909101519092509050816132be575050506116c7565b7f474c763ff84bf2c2039a6d9fea955ecd0f724030e3c365b91169c6a16fe751b78585600360009054906101000a90046001600160a01b03166001600160a01b031663318bc6896040518163ffffffff1660e01b815260040160206040518083038186803b15801561332f57600080fd5b505afa158015613343573d6000803e3d6000fd5b505050506040513d602081101561335957600080fd5b5051604080516001600160a01b03948516815260208101939093528281019190915260608201869052918416608082015290519081900360a00190a15050505050565b804710156133f1576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e6365000000604482015290519081900360640190fd5b6040516000906001600160a01b0384169083908381818185875af1925050503d806000811461343c576040519150601f19603f3d011682016040523d82523d6000602084013e613441565b606091505b50509050806134815760405162461bcd60e51b815260040180806020018281038252603a815260200180614dcc603a913960400191505060405180910390fd5b505050565b6003546000906001600160a01b0316818561351957816001600160a01b031663e124e6d28a6040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156134e857600080fd5b505afa1580156134fc573d6000803e3d6000fd5b505050506040513d602081101561351257600080fd5b5051613593565b816001600160a01b03166381a612d68a6040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561356657600080fd5b505afa15801561357a573d6000803e3d6000fd5b505050506040513d602081101561359057600080fd5b50515b905085156135df57838110156135da5760405162461bcd60e51b8152600401808060200182810382526030815260200180614e2c6030913960400191505060405180910390fd5b61361e565b8381111561361e5760405162461bcd60e51b8152600401808060200182810382526031815260200180614ecc6031913960400191505060405180910390fd5b6000826001600160a01b03166312d43a516040518163ffffffff1660e01b815260040160206040518083038186803b15801561365957600080fd5b505afa15801561366d573d6000803e3d6000fd5b505050506040513d602081101561368357600080fd5b81019080805190602001909291905050509050600460009054906101000a90046001600160a01b03166001600160a01b031663f3238cec8d8d8d8b8d8860006040518863ffffffff1660e01b815260040180886001600160a01b03168152602001876001600160a01b03168152602001866001600160a01b0316815260200185151581526020018481526020018381526020018215158152602001975050505050505050600060405180830381600087803b15801561374157600080fd5b505af1158015613755573d6000803e3d6000fd5b50505050806001600160a01b0316636d63c1d0846040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b1580156137a857600080fd5b505af11580156137bc573d6000803e3d6000fd5b505050506000600560009054906101000a90046001600160a01b03166001600160a01b0316632662166b8e8e8e8e8e8e8e6040518863ffffffff1660e01b815260040180886001600160a01b03168152602001876001600160a01b03168152602001866001600160a01b031681526020018581526020018481526020018315158152602001826001600160a01b03168152602001975050505050505050602060405180830381600087803b15801561387357600080fd5b505af1158015613887573d6000803e3d6000fd5b505050506040513d602081101561389d57600080fd5b50516040805163d3c87bbb60e01b81526001600160a01b03878116600483015291519293509084169163d3c87bbb9160248082019260009290919082900301818387803b1580156138ed57600080fd5b505af1158015613901573d6000803e3d6000fd5b5050505061390f8d8a613213565b9c9b505050505050505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052613481908490614400565b60008351600214156139b8576139b18460008151811061398d57fe5b6020026020010151856001815181106139a257fe5b602002602001015185856144b1565b90506139ef565b60405162461bcd60e51b8152600401808060200182810382526029815260200180614f446029913960400191505060405180910390fd5b9392505050565b60065460408051632e1a7d4d60e01b81526004810185905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b158015613a4357600080fd5b505af1158015613a57573d6000803e3d6000fd5b50506040516001600160a01b038416925084156108fc02915084906000818181858888f150505050505050565b3415613aee57600660009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b158015613ada57600080fd5b505af1158015612f0c573d6000803e3d6000fd5b565b600080613b01888888888888614587565b90508015613bc0576000613b38612710613b32613b2b60075461271061476490919063ffffffff16565b8a906147af565b90614808565b90506000613b468883614764565b905060008960018b510381518110613b5a57fe5b60200260200101519050613b9c82600a6000846001600160a01b03166001600160a01b031681526020019081526020016000205461484790919063ffffffff16565b6001600160a01b039091166000908152600a6020526040902055509150613bc59050565b859150505b9695505050505050565b6003546001600160a01b0316600083613c6057816001600160a01b03166381a612d6876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015613c2f57600080fd5b505afa158015613c43573d6000803e3d6000fd5b505050506040513d6020811015613c5957600080fd5b5051613cda565b816001600160a01b031663e124e6d2876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015613cad57600080fd5b505afa158015613cc1573d6000803e3d6000fd5b505050506040513d6020811015613cd757600080fd5b50515b90508315613d265782811115613d215760405162461bcd60e51b8152600401808060200182810382526031815260200180614ecc6031913960400191505060405180910390fd5b613d65565b82811015613d655760405162461bcd60e51b8152600401808060200182810382526030815260200180614e2c6030913960400191505060405180910390fd5b613d7086858761489f565b6000826001600160a01b03166312d43a516040518163ffffffff1660e01b815260040160206040518083038186803b158015613dab57600080fd5b505afa158015613dbf573d6000803e3d6000fd5b505050506040513d6020811015613dd557600080fd5b50516004805460408051633cc8e33b60e21b81526001600160a01b038e8116948201949094528c841660248201528b841660448201528915156064820152608481018b905260a48101879052600160c4820152905193945091169163f3238cec9160e48082019260009290919082900301818387803b158015613e5757600080fd5b505af1158015613e6b573d6000803e3d6000fd5b50505050806001600160a01b0316636d63c1d0846040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015613ebe57600080fd5b505af1158015613ed2573d6000803e3d6000fd5b505060055460408051630f8ee8bb60e11b81526001600160a01b038e811660048301528d811660248301528c81166044830152606482018c90528a151560848301529151919092169350631f1dd176925060a480830192600092919082900301818387803b158015613f4357600080fd5b505af1158015613f57573d6000803e3d6000fd5b50505050806001600160a01b031663d3c87bbb846040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015613faa57600080fd5b505af1158015613fbe573d6000803e3d6000fd5b50505050613fcc89876142fa565b505050505050505050565b600d546040805163d3bab1d160e01b81526001600160a01b03858116600483015260248201859052915160009384938493849384938493169163d3bab1d191604480830192610120929190829003018186803b15801561403657600080fd5b505afa15801561404a573d6000803e3d6000fd5b505050506040513d61012081101561406157600080fd5b508051602082015160408301516060840151608085015160a090950151939a5091985096509450909250905061409883828461489f565b600d54600160a81b900460ff166140b4575050505050506116c7565b806140c4575050505050506116c7565b60008211614119576040805162461bcd60e51b815260206004820152601d60248201527f506f736974696f6e4d616e616765723a206c6f6e67206465706f736974000000604482015290519081900360640190fd5b60035460408051634a3f088d60e01b81526001600160a01b038b811660048301528781166024830152868116604483015284151560648301529151919092169160009182918491634a3f088d9160848082019261010092909190829003018186803b15801561418757600080fd5b505afa15801561419b573d6000803e3d6000fd5b505050506040513d6101008110156141b257600080fd5b5080516020909101519092509050816141d3575050505050505050506116c7565b60006141df8387614847565b90506000846001600160a01b0316630a48d5a98c8c6040518363ffffffff1660e01b815260040180836001600160a01b031681526020018281526020019250505060206040518083038186803b15801561423857600080fd5b505afa15801561424c573d6000803e3d6000fd5b505050506040513d602081101561426257600080fd5b5051905060006142728483614847565b9050600061428685613b32886127106147af565b905060006142a783613b3260085461271001886147af90919063ffffffff16565b9050818110156142e85760405162461bcd60e51b8152600401808060200182810382526027815260200180614f1d6027913960400191505060405180910390fd5b50505050505050505050505050505050565b6009546001600160a01b03168061431157506116c7565b600080826001600160a01b031663534ef883866040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050604080518083038186803b15801561436057600080fd5b505afa158015614374573d6000803e3d6000fd5b505050506040513d604081101561438a57600080fd5b5080516020918201516003546040805163318bc68960e01b815290519396509194507fc2414023ce7002ee98557d1e7be21e5559073336f2217ee5f9b2e50fd85f71ee93899389936001600160a01b039093169263318bc689926004808301939192829003018186803b15801561332f57600080fd5b6060614455826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614a579092919063ffffffff16565b8051909150156134815780806020019051602081101561447457600080fd5b50516134815760405162461bcd60e51b815260040180806020018281038252602a815260200180614fb9602a913960400191505060405180910390fd5b60035460408051634998b10960e11b81526001600160a01b03878116600483015286811660248301528481166044830152915160009384931691639331621291606480830192602092919082900301818787803b15801561451157600080fd5b505af1158015614525573d6000803e3d6000fd5b505050506040513d602081101561453b57600080fd5b505190508381101561457e5760405162461bcd60e51b815260040180806020018281038252602b815260200180614da1602b913960400191505060405180910390fd5b95945050505050565b60008261459657506000613bc5565b816145a357506001613bc5565b6000866001885103815181106145b557fe5b602090810291909101015160035460408051634a3f088d60e01b81526001600160a01b038c81166004830152808516602483015289811660448301528815156064830152915193945091169160009182918491634a3f088d91608480830192610100929190829003018186803b15801561462e57600080fd5b505afa158015614642573d6000803e3d6000fd5b505050506040513d61010081101561465957600080fd5b508051602090910151909250905081614679576000945050505050613bc5565b60006146858388614847565b90506000846001600160a01b0316630a48d5a9878d6040518363ffffffff1660e01b815260040180836001600160a01b031681526020018281526020019250505060206040518083038186803b1580156146de57600080fd5b505afa1580156146f2573d6000803e3d6000fd5b505050506040513d602081101561470857600080fd5b5051905060006147188483614847565b9050600061472c85613b32886127106147af565b9050600061474d83613b3260085461271001886147af90919063ffffffff16565b919091109f9e505050505050505050505050505050565b60006147a683836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250614a6e565b90505b92915050565b6000826147be575060006147a9565b828202828482816147cb57fe5b04146147a65760405162461bcd60e51b8152600401808060200182810382526021815260200180614eab6021913960400191505060405180910390fd5b60006147a683836040518060400160405280601a815260200179536166654d6174683a206469766973696f6e206279207a65726f60301b815250614b05565b6000828201838110156147a6576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b806148a957613481565b811561499c576001600160a01b0383166000908152600b6020526040902054801580159061495a57506003546040805163783a2b6760e11b81526001600160a01b0387811660048301529151849361495893879391169163f07456ce91602480820192602092909190829003018186803b15801561492657600080fd5b505afa15801561493a573d6000803e3d6000fd5b505050506040513d602081101561495057600080fd5b505190614847565b115b156149965760405162461bcd60e51b815260040180806020018281038252602e815260200180614d33602e913960400191505060405180910390fd5b50613481565b6001600160a01b0383166000908152600c60205260409020548015801590614a1557506003546040805163114f1b5560e31b81526001600160a01b03878116600483015291518493614a13938793911691638a78daa891602480820192602092909190829003018186803b15801561492657600080fd5b115b15614a515760405162461bcd60e51b815260040180806020018281038252602f815260200180614e7c602f913960400191505060405180910390fd5b50505050565b6060614a668484600085614b6a565b949350505050565b60008184841115614afd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015614ac2578181015183820152602001614aaa565b50505050905090810190601f168015614aef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b60008183614b545760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315614ac2578181015183820152602001614aaa565b506000838581614b6057fe5b0495945050505050565b606082471015614bab5760405162461bcd60e51b8152600401808060200182810382526026815260200180614e066026913960400191505060405180910390fd5b614bb485614cc6565b614c05576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b60208310614c445780518252601f199092019160209182019101614c25565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114614ca6576040519150601f19603f3d011682016040523d82523d6000602084013e614cab565b606091505b5091509150614cbb828286614ccc565b979650505050505050565b3b151590565b60608315614cdb5750816139ef565b825115614ceb5782518084602001fd5b60405162461bcd60e51b8152602060048201818152845160248401528451859391928392604401919085019080838360008315614ac2578181015183820152602001614aaa56fe42617365506f736974696f6e4d616e616765723a206d617820676c6f62616c206c6f6e67732065786365656465645265656e7472616e637947756172643a207265656e7472616e742063616c6c00476f7665726e61626c653a20666f7262696464656e000000000000000000000042617365506f736974696f6e4d616e616765723a20696e73756666696369656e7420616d6f756e744f7574416464726573733a20756e61626c6520746f2073656e642076616c75652c20726563697069656e74206d61792068617665207265766572746564416464726573733a20696e73756666696369656e742062616c616e636520666f722063616c6c42617365506f736974696f6e4d616e616765723a206d61726b207072696365206c6f776572207468616e206c696d697442617365506f736974696f6e4d616e616765723a20666f7262696464656e000042617365506f736974696f6e4d616e616765723a206d617820676c6f62616c2073686f727473206578636565646564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7742617365506f736974696f6e4d616e616765723a206d61726b20707269636520686967686572207468616e206c696d6974506f736974696f6e4d616e616765723a20666f7262696464656e000000000000506f736974696f6e4d616e616765723a206c6f6e67206c6576657261676520646563726561736542617365506f736974696f6e4d616e616765723a20696e76616c6964205f706174682e6c656e677468506f736974696f6e4d616e616765723a20696e76616c6964205f636f6c6c61746572616c546f6b656e42617365506f736974696f6e4d616e616765723a20696e76616c69642073656e6465725361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564506f736974696f6e4d616e616765723a20696e76616c6964205f706174682e6c656e677468a2646970667358221220d46b9214685488ef5208db15114ce1f5b375887b041ec6561b9271132a6bfb4664736f6c634300060c0033000000000000000000000000096eedffad8678ed8d74fcdcf71c3c28ebae06490000000000000000000000001b1d7b2756e57d7ff45f3a42fafc4f9b419956460000000000000000000000005f3d354e6c6f57bc891a405251bb898af6b4d0ca000000000000000000000000c86c7c0efbd6a49b35e8714c5f59d99de09a225b000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000368ab183ce0b1acef4f8262fa04596dac2d61633
Deployed ByteCode
0x6080604052600436106101ff5760003560e01c8063657bc5d011610114578063657bc5d0146107da57806367a52793146107ef578063704b6c0214610804578063776af5ba146108375780638c0f9aac1461084c57806390205d8c1461087f5780639698d25a146108de57806398d1e03a146109115780639c95332f14610926578063ae4d7f9a14610952578063b32755de14610985578063b7ddc99214610a48578063cfad57a214610b1e578063d38ab51914610b51578063d4ca83f914610b94578063de2ea94814610ba9578063e1f21c6714610bfe578063ef12c67e14610c41578063f255527814610df3578063f851a44014610e2e578063f887ea4014610e43578063fbfa77cf14610e585761024f565b80626cc35e1461025457806307c7edc3146102855780631045c74e146102c857806311d9444a1461030d578063126082cf1461035057806312d43a51146103655780631b9043591461037a5780631ce9cb8f146103a65780631e261538146103d957806321acf65914610414578063233bfe3b1461044f57806324a084df146104795780633039e37f146104b25780633833f5f5146105925780633fc8cef3146105d9578063430ed37c146105ee5780634453a3741461064d5780634584bd4b14610688578063490ae2101461069d578063529a356f146106c75780635fc8500e146106fa5761024f565b3661024f576006546001600160a01b0316331461024d5760405162461bcd60e51b8152600401808060200182810382526023815260200180614f966023913960400191505060405180910390fd5b005b600080fd5b34801561026057600080fd5b50610269610e6d565b604080516001600160a01b039092168252519081900360200190f35b34801561029157600080fd5b5061024d600480360360608110156102a857600080fd5b506001600160a01b03813581169160208101359160409091013516610e7c565b3480156102d457600080fd5b506102fb600480360360208110156102eb57600080fd5b50356001600160a01b0316610f48565b60408051918252519081900360200190f35b34801561031957600080fd5b5061024d6004803603606081101561033057600080fd5b506001600160a01b03813581169160208101359160409091013516610f5a565b34801561035c57600080fd5b506102fb6113ba565b34801561037157600080fd5b506102696113c0565b34801561038657600080fd5b5061024d6004803603602081101561039d57600080fd5b503515156113cf565b3480156103b257600080fd5b506102fb600480360360208110156103c957600080fd5b50356001600160a01b031661146f565b3480156103e557600080fd5b5061024d600480360360408110156103fc57600080fd5b506001600160a01b0381351690602001351515611481565b34801561042057600080fd5b5061024d6004803603604081101561043757600080fd5b506001600160a01b038135169060200135151561152e565b34801561045b57600080fd5b5061024d6004803603602081101561047257600080fd5b50356115df565b34801561048557600080fd5b5061024d6004803603604081101561049c57600080fd5b506001600160a01b038135169060200135611667565b3480156104be57600080fd5b5061024d60048036036101008110156104d657600080fd5b810190602081018135600160201b8111156104f057600080fd5b82018360208201111561050257600080fd5b803590602001918460208302840111600160201b8311171561052357600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505081356001600160a01b0390811693506020830135926040810135925060608101351515916080820135169060a08101359060c001356116cb565b34801561059e57600080fd5b506105c5600480360360208110156105b557600080fd5b50356001600160a01b03166118d8565b604080519115158252519081900360200190f35b3480156105e557600080fd5b506102696118ed565b3480156105fa57600080fd5b5061024d600480360360e081101561061157600080fd5b506001600160a01b0381358116916020810135821691604082013591606081013591608082013515159160a08101359091169060c001356118fc565b34801561065957600080fd5b5061024d6004803603604081101561067057600080fd5b506001600160a01b0381351690602001351515611a25565b34801561069457600080fd5b506105c5611ad2565b3480156106a957600080fd5b5061024d600480360360208110156106c057600080fd5b5035611ae2565b3480156106d357600080fd5b506105c5600480360360208110156106ea57600080fd5b50356001600160a01b0316611b6a565b34801561070657600080fd5b5061024d600480360361010081101561071e57600080fd5b810190602081018135600160201b81111561073857600080fd5b82018360208201111561074a57600080fd5b803590602001918460208302840111600160201b8311171561076b57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505081356001600160a01b0390811693506020830135926040810135925060608101351515916080820135169060a08101359060c00135611b7f565b3480156107e657600080fd5b50610269611cb6565b3480156107fb57600080fd5b506102fb611cc5565b34801561081057600080fd5b5061024d6004803603602081101561082757600080fd5b50356001600160a01b0316611ccb565b34801561084357600080fd5b50610269611d6c565b34801561085857600080fd5b506105c56004803603602081101561086f57600080fd5b50356001600160a01b0316611d7b565b34801561088b57600080fd5b5061024d600480360360e08110156108a257600080fd5b506001600160a01b0381358116916020810135821691604082013591606081013591608082013515159160a08101359091169060c00135611d90565b3480156108ea57600080fd5b506102fb6004803603602081101561090157600080fd5b50356001600160a01b0316611e50565b34801561091d57600080fd5b506102fb611e62565b34801561093257600080fd5b5061024d6004803603602081101561094957600080fd5b50351515611e68565b34801561095e57600080fd5b5061024d6004803603602081101561097557600080fd5b50356001600160a01b0316611f08565b61024d600480360360c081101561099b57600080fd5b810190602081018135600160201b8111156109b557600080fd5b8201836020820111156109c757600080fd5b803590602001918460208302840111600160201b831117156109e857600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550506001600160a01b0383351693505050602081013590604081013590606081013515159060800135611fa9565b348015610a5457600080fd5b5061024d600480360360e0811015610a6b57600080fd5b810190602081018135600160201b811115610a8557600080fd5b820183602082011115610a9757600080fd5b803590602001918460208302840111600160201b83111715610ab857600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550506001600160a01b0383351693505050602081013590604081013590606081013590608081013515159060a001356121da565b348015610b2a57600080fd5b5061024d60048036036020811015610b4157600080fd5b50356001600160a01b03166124b9565b348015610b5d57600080fd5b5061024d60048036036060811015610b7457600080fd5b506001600160a01b03813581169160208101359160409091013516612528565b348015610ba057600080fd5b506105c5612989565b348015610bb557600080fd5b5061024d600480360360a0811015610bcc57600080fd5b506001600160a01b03813581169160208101358216916040820135811691606081013515159160809091013516612999565b348015610c0a57600080fd5b5061024d60048036036060811015610c2157600080fd5b506001600160a01b03813581169160208101359091169060400135612e3e565b348015610c4d57600080fd5b5061024d60048036036060811015610c6457600080fd5b810190602081018135600160201b811115610c7e57600080fd5b820183602082011115610c9057600080fd5b803590602001918460208302840111600160201b83111715610cb157600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610d0057600080fd5b820183602082011115610d1257600080fd5b803590602001918460208302840111600160201b83111715610d3357600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610d8257600080fd5b820183602082011115610d9457600080fd5b803590602001918460208302840111600160201b83111715610db557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612f13945050505050565b348015610dff57600080fd5b5061024d60048036036040811015610e1657600080fd5b506001600160a01b0381358116916020013516613102565b348015610e3a57600080fd5b506102696131e6565b348015610e4f57600080fd5b506102696131f5565b348015610e6457600080fd5b50610269613204565b6009546001600160a01b031681565b336000908152600e602052604090205460ff16610ece576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b600d54604080516307c7edc360e01b81526001600160a01b038681166004830152602482018690528481166044830152915191909216916307c7edc391606480830192600092919082900301818387803b158015610f2b57600080fd5b505af1158015610f3f573d6000803e3d6000fd5b50505050505050565b600b6020526000908152604090205481565b336000908152600e602052604090205460ff16610fac576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b600354604080516312d43a5160e01b815290516001600160a01b039092169160009183916312d43a5191600480820192602092909190829003018186803b158015610ff657600080fd5b505afa15801561100a573d6000803e3d6000fd5b505050506040513d602081101561102057600080fd5b5051600d5460408051630130197760e11b81526001600160a01b03898116600483015260248201899052915193945060009384938493849391169163026032ee9160448082019261010092909190829003018186803b15801561108257600080fd5b505afa158015611096573d6000803e3d6000fd5b505050506040513d6101008110156110ad57600080fd5b508051604082015160608301516080909301519196509450909250905060008161114f57866001600160a01b031663e124e6d2856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561111e57600080fd5b505afa158015611132573d6000803e3d6000fd5b505050506040513d602081101561114857600080fd5b50516111c9565b866001600160a01b03166381a612d6856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561119c57600080fd5b505afa1580156111b0573d6000803e3d6000fd5b505050506040513d60208110156111c657600080fd5b50515b6004805460408051633cc8e33b60e21b81526001600160a01b038f8116948201949094528984166024820152888416604482015286151560648201526084810188905260a48101859052600060c482018190529151949550929091169263f3238cec9260e480820193929182900301818387803b15801561124957600080fd5b505af115801561125d573d6000803e3d6000fd5b50505050856001600160a01b0316636d63c1d0886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b1580156112b057600080fd5b505af11580156112c4573d6000803e3d6000fd5b5050600d54604080516308eca22560e11b81526001600160a01b038f81166004830152602482018f90528d8116604483015291519190921693506311d9444a9250606480830192600092919082900301818387803b15801561132557600080fd5b505af1158015611339573d6000803e3d6000fd5b50505050856001600160a01b031663d3c87bbb886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b15801561138c57600080fd5b505af11580156113a0573d6000803e3d6000fd5b505050506113ae8a84613213565b50505050505050505050565b61271081565b6001546001600160a01b031681565b6002546001600160a01b0316331461141c576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b600d8054821515600160a81b810260ff60a81b199092169190911790915560408051918252517fa956222e37fe025ff51e5440ac729a9bd417ff91e485e14dcffa2c0ba8894f409181900360200190a150565b600a6020526000908152604090205481565b6002546001600160a01b031633146114ce576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b0382166000818152600e6020908152604091829020805460ff1916851515908117909155825190815291517f1d5bc0255b943d6a5b5279e8a55d74d620baccbceecb25e87a3558f14c4c118e9281900390910190a25050565b6002546001600160a01b0316331461157b576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b0382166000818152600f6020908152604091829020805460ff191685151590811790915582519384529083015280517fa4e46c70ff429a91de7d1716d736e877c7cca1c22ac850b23d242530dd95e4749281900390910190a15050565b6002546001600160a01b0316331461162c576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b60088190556040805182815290517f21167d0d4661af93817ebce920f18986eed3d75d5e1c03f2aed05efcbafbc4529181900360200190a150565b6001546001600160a01b031633146116b4576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b6116c76001600160a01b0383168261339c565b5050565b60026000541415611711576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061173c5750600d54600160a01b900460ff165b61177b576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b87516002146117bb5760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b60065488516001600160a01b0390911690899060001981019081106117dc57fe5b60200260200101516001600160a01b03161461183f576040805162461bcd60e51b815260206004820152601e60248201527f506f736974696f6e4d616e616765723a20696e76616c6964205f706174680000604482015290519081900360640190fd5b6000611865338a60008151811061185257fe5b60200260200101518a8a8a8a308a613486565b90506118ae600360009054906101000a90046001600160a01b0316828b60008151811061188e57fe5b60200260200101516001600160a01b031661391f9092919063ffffffff16565b60006118bb8a8430613971565b90506118c781866139f6565b505060016000555050505050505050565b600e6020526000908152604090205460ff1681565b6006546001600160a01b031681565b60026000541415611942576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061196d5750600d54600160a01b900460ff165b6119ac576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b6006546001600160a01b038881169116146119f85760405162461bcd60e51b8152600401808060200182810382526029815260200180614f6d6029913960400191505060405180910390fd5b6000611a0a3389898989893089613486565b9050611a1681846139f6565b50506001600055505050505050565b6002546001600160a01b03163314611a72576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b038216600081815260106020908152604091829020805460ff1916851515908117909155825190815291517f8c0d56805c3b43d441481229dc64bee168253ffe4305f37ab7cfe63b1c4268c69281900390910190a25050565b600d54600160a81b900460ff1681565b6002546001600160a01b03163314611b2f576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b60078190556040805182815290517f974fd3c1fcb4653dfc4fb740c4c692cd212d55c28f163f310128cb64d83006759181900360200190a150565b60106020526000908152604090205460ff1681565b60026000541415611bc5576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff1680611bf05750600d54600160a01b900460ff165b611c2f576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b8751600214611c6f5760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b6000611c82338a60008151811061185257fe5b9050611cab600360009054906101000a90046001600160a01b0316828b60008151811061188e57fe5b6118c7898386613971565b6004546001600160a01b031681565b60075481565b6001546001600160a01b03163314611d18576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b600280546001600160a01b0383166001600160a01b0319909116811790915560408051918252517f5a272403b402d892977df56625f4164ccaf70ca3863991c43ecfe76a6905b0a19181900360200190a150565b600d546001600160a01b031681565b600f6020526000908152604090205460ff1681565b60026000541415611dd6576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff1680611e015750600d54600160a01b900460ff165b611e40576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b611a163388888888888888613486565b600c6020526000908152604090205481565b60085481565b6002546001600160a01b03163314611eb5576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b600d8054821515600160a01b810260ff60a01b199092169190911790915560408051918252517feac6b3611e79ff0d8ea5daa8439f6b1ab7eea4ebf95f1dd360417f712c3fc3049181900360200190a150565b6002546001600160a01b03163314611f55576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b600980546001600160a01b0383166001600160a01b0319909116811790915560408051918252517f828abcccea18192c21d645e575652c49e20b986dab777906fc473d056b01b6a89181900360200190a150565b60026000541415611fef576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061201a5750600d54600160a01b900460ff165b612059576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b85516001148061206a575085516002145b6120a55760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b60065486516001600160a01b039091169087906000906120c157fe5b60200260200101516001600160a01b031614612124576040805162461bcd60e51b815260206004820152601e60248201527f506f736974696f6e4d616e616765723a20696e76616c6964205f706174680000604482015290519081900360640190fd5b34156121a857612132613a84565b85513490600110156121695760035460065461215b916001600160a01b0391821691163461391f565b612166878630613971565b90505b60006121793389848a888a613af0565b90506121a5600360009054906101000a90046001600160a01b0316828a60018c51038151811061188e57fe5b50505b6121cd33876001895103815181106121bc57fe5b602002602001015187868686613bcf565b5050600160005550505050565b60026000541415612220576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b60026000908155338152600f602052604090205460ff168061224b5750600d54600160a01b900460ff165b61228a576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b86516001148061229b575086516002145b6122d65760405162461bcd60e51b8152600401808060200182810382526025815260200180614fe36025913960400191505060405180910390fd5b8415612486578651600114156123965760055487516001600160a01b0390911690631b82787890899060009061230857fe5b60200260200101513330896040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846001600160a01b03168152602001836001600160a01b03168152602001828152602001945050505050600060405180830381600087803b15801561237957600080fd5b505af115801561238d573d6000803e3d6000fd5b50505050612448565b60055487516001600160a01b0390911690631b8278789089906000906123b857fe5b6020908102919091010151600354604080516001600160e01b031960e086901b1681526001600160a01b0393841660048201523360248201529290911660448301526064820189905251608480830192600092919082900301818387803b15801561242257600080fd5b505af1158015612436573d6000803e3d6000fd5b50505050612445878530613971565b94505b60006124583389888a8789613af0565b9050612484600360009054906101000a90046001600160a01b0316828a60018c51038151811061188e57fe5b505b6124ab338860018a51038151811061249a57fe5b602002602001015188868686613bcf565b505060016000555050505050565b6001546001600160a01b03163314612506576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b336000908152600e602052604090205460ff1661257a576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b6125848383613fd7565b600354604080516312d43a5160e01b815290516001600160a01b039092169160009183916312d43a5191600480820192602092909190829003018186803b1580156125ce57600080fd5b505afa1580156125e2573d6000803e3d6000fd5b505050506040513d60208110156125f857600080fd5b5051600d546040805163d3bab1d160e01b81526001600160a01b03898116600483015260248201899052915193945060009384938493849391169163d3bab1d19160448082019261012092909190829003018186803b15801561265a57600080fd5b505afa15801561266e573d6000803e3d6000fd5b505050506040513d61012081101561268557600080fd5b5060408101516060820151608083015160a0909301519196509450909250905060008161272a57866001600160a01b03166381a612d6856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156126f957600080fd5b505afa15801561270d573d6000803e3d6000fd5b505050506040513d602081101561272357600080fd5b50516127a4565b866001600160a01b031663e124e6d2856040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561277757600080fd5b505afa15801561278b573d6000803e3d6000fd5b505050506040513d60208110156127a157600080fd5b50515b6004805460408051633cc8e33b60e21b81526001600160a01b038f8116948201949094528984166024820152888416604482015286151560648201526084810188905260a48101859052600160c4820152905193945091169163f3238cec9160e48082019260009290919082900301818387803b15801561282457600080fd5b505af1158015612838573d6000803e3d6000fd5b50505050856001600160a01b0316636d63c1d0886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b15801561288b57600080fd5b505af115801561289f573d6000803e3d6000fd5b5050600d546040805163d38ab51960e01b81526001600160a01b038f81166004830152602482018f90528d81166044830152915191909216935063d38ab5199250606480830192600092919082900301818387803b15801561290057600080fd5b505af1158015612914573d6000803e3d6000fd5b50505050856001600160a01b031663d3c87bbb886040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b15801561296757600080fd5b505af115801561297b573d6000803e3d6000fd5b505050506113ae8a846142fa565b600d54600160a01b900460ff1681565b600260005414156129df576040805162461bcd60e51b815260206004820152601f6024820152600080516020614d61833981519152604482015290519081900360640190fd5b600260009081553381526010602052604090205460ff16612a35576040805162461bcd60e51b815260206004820152601a6024820152600080516020614efd833981519152604482015290519081900360640190fd5b600354604080516312d43a5160e01b815290516001600160a01b039092169160009183916312d43a5191600480820192602092909190829003018186803b158015612a7f57600080fd5b505afa158015612a93573d6000803e3d6000fd5b505050506040513d6020811015612aa957600080fd5b505160035460408051634a3f088d60e01b81526001600160a01b038b811660048301528a811660248301528981166044830152881515606483015291519394506000939190921691634a3f088d91608480830192610100929190829003018186803b158015612b1757600080fd5b505afa158015612b2b573d6000803e3d6000fd5b505050506040513d610100811015612b4257600080fd5b50519050600085612bcb57836001600160a01b031663e124e6d2886040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015612b9a57600080fd5b505afa158015612bae573d6000803e3d6000fd5b505050506040513d6020811015612bc457600080fd5b5051612c45565b836001600160a01b03166381a612d6886040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015612c1857600080fd5b505afa158015612c2c573d6000803e3d6000fd5b505050506040513d6020811015612c4257600080fd5b50515b6004805460408051633cc8e33b60e21b81526001600160a01b038e8116948201949094528c841660248201528b841660448201528a151560648201526084810187905260a48101859052600060c482018190529151949550929091169263f3238cec9260e480820193929182900301818387803b158015612cc557600080fd5b505af1158015612cd9573d6000803e3d6000fd5b50505050826001600160a01b0316636d63c1d0856040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015612d2c57600080fd5b505af1158015612d40573d6000803e3d6000fd5b505060408051631bc5d52960e31b81526001600160a01b038d811660048301528c811660248301528b811660448301528a1515606483015289811660848301529151918816935063de2ea948925060a48082019260009290919082900301818387803b158015612daf57600080fd5b505af1158015612dc3573d6000803e3d6000fd5b50505050826001600160a01b031663d3c87bbb856040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015612e1657600080fd5b505af1158015612e2a573d6000803e3d6000fd5b505060016000555050505050505050505050565b6001546001600160a01b03163314612e8b576040805162461bcd60e51b81526020600482015260156024820152600080516020614d81833981519152604482015290519081900360640190fd5b826001600160a01b031663095ea7b383836040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050602060405180830381600087803b158015612ee257600080fd5b505af1158015612ef6573d6000803e3d6000fd5b505050506040513d6020811015612f0c57600080fd5b5050505050565b6002546001600160a01b03163314612f60576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b60005b8351811015612ffb576000848281518110612f7a57fe5b60200260200101519050838281518110612f9057fe5b6020026020010151600b6000836001600160a01b03166001600160a01b0316815260200190815260200160002081905550828281518110612fcd57fe5b6020908102919091018101516001600160a01b039092166000908152600c9091526040902055600101612f63565b507fae32d569b058895b9620d6552b09aaffedc9a6f396be4d595a224ad09f8b213983838360405180806020018060200180602001848103845287818151815260200191508051906020019060200280838360005b83811015613068578181015183820152602001613050565b50505050905001848103835286818151815260200191508051906020019060200280838360005b838110156130a757818101518382015260200161308f565b50505050905001848103825285818151815260200191508051906020019060200280838360005b838110156130e65781810151838201526020016130ce565b50505050905001965050505050505060405180910390a1505050565b6002546001600160a01b0316331461314f576040805162461bcd60e51b815260206004820152601e6024820152600080516020614e5c833981519152604482015290519081900360640190fd5b6001600160a01b0382166000908152600a60205260409020548061317357506116c7565b6001600160a01b0383166000818152600a602052604081205561319790838361391f565b604080516001600160a01b0380861682528416602082015280820183905290517f4f1b51dd7a2fcb861aa2670f668be66835c4ee12b4bbbf037e4d0018f39819e49181900360600190a1505050565b6002546001600160a01b031681565b6005546001600160a01b031681565b6003546001600160a01b031681565b6009546001600160a01b03168061322a57506116c7565b600080826001600160a01b031663534ef883866040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050604080518083038186803b15801561327957600080fd5b505afa15801561328d573d6000803e3d6000fd5b505050506040513d60408110156132a357600080fd5b5080516020909101519092509050816132be575050506116c7565b7f474c763ff84bf2c2039a6d9fea955ecd0f724030e3c365b91169c6a16fe751b78585600360009054906101000a90046001600160a01b03166001600160a01b031663318bc6896040518163ffffffff1660e01b815260040160206040518083038186803b15801561332f57600080fd5b505afa158015613343573d6000803e3d6000fd5b505050506040513d602081101561335957600080fd5b5051604080516001600160a01b03948516815260208101939093528281019190915260608201869052918416608082015290519081900360a00190a15050505050565b804710156133f1576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e6365000000604482015290519081900360640190fd5b6040516000906001600160a01b0384169083908381818185875af1925050503d806000811461343c576040519150601f19603f3d011682016040523d82523d6000602084013e613441565b606091505b50509050806134815760405162461bcd60e51b815260040180806020018281038252603a815260200180614dcc603a913960400191505060405180910390fd5b505050565b6003546000906001600160a01b0316818561351957816001600160a01b031663e124e6d28a6040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156134e857600080fd5b505afa1580156134fc573d6000803e3d6000fd5b505050506040513d602081101561351257600080fd5b5051613593565b816001600160a01b03166381a612d68a6040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561356657600080fd5b505afa15801561357a573d6000803e3d6000fd5b505050506040513d602081101561359057600080fd5b50515b905085156135df57838110156135da5760405162461bcd60e51b8152600401808060200182810382526030815260200180614e2c6030913960400191505060405180910390fd5b61361e565b8381111561361e5760405162461bcd60e51b8152600401808060200182810382526031815260200180614ecc6031913960400191505060405180910390fd5b6000826001600160a01b03166312d43a516040518163ffffffff1660e01b815260040160206040518083038186803b15801561365957600080fd5b505afa15801561366d573d6000803e3d6000fd5b505050506040513d602081101561368357600080fd5b81019080805190602001909291905050509050600460009054906101000a90046001600160a01b03166001600160a01b031663f3238cec8d8d8d8b8d8860006040518863ffffffff1660e01b815260040180886001600160a01b03168152602001876001600160a01b03168152602001866001600160a01b0316815260200185151581526020018481526020018381526020018215158152602001975050505050505050600060405180830381600087803b15801561374157600080fd5b505af1158015613755573d6000803e3d6000fd5b50505050806001600160a01b0316636d63c1d0846040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b1580156137a857600080fd5b505af11580156137bc573d6000803e3d6000fd5b505050506000600560009054906101000a90046001600160a01b03166001600160a01b0316632662166b8e8e8e8e8e8e8e6040518863ffffffff1660e01b815260040180886001600160a01b03168152602001876001600160a01b03168152602001866001600160a01b031681526020018581526020018481526020018315158152602001826001600160a01b03168152602001975050505050505050602060405180830381600087803b15801561387357600080fd5b505af1158015613887573d6000803e3d6000fd5b505050506040513d602081101561389d57600080fd5b50516040805163d3c87bbb60e01b81526001600160a01b03878116600483015291519293509084169163d3c87bbb9160248082019260009290919082900301818387803b1580156138ed57600080fd5b505af1158015613901573d6000803e3d6000fd5b5050505061390f8d8a613213565b9c9b505050505050505050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052613481908490614400565b60008351600214156139b8576139b18460008151811061398d57fe5b6020026020010151856001815181106139a257fe5b602002602001015185856144b1565b90506139ef565b60405162461bcd60e51b8152600401808060200182810382526029815260200180614f446029913960400191505060405180910390fd5b9392505050565b60065460408051632e1a7d4d60e01b81526004810185905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b158015613a4357600080fd5b505af1158015613a57573d6000803e3d6000fd5b50506040516001600160a01b038416925084156108fc02915084906000818181858888f150505050505050565b3415613aee57600660009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b158015613ada57600080fd5b505af1158015612f0c573d6000803e3d6000fd5b565b600080613b01888888888888614587565b90508015613bc0576000613b38612710613b32613b2b60075461271061476490919063ffffffff16565b8a906147af565b90614808565b90506000613b468883614764565b905060008960018b510381518110613b5a57fe5b60200260200101519050613b9c82600a6000846001600160a01b03166001600160a01b031681526020019081526020016000205461484790919063ffffffff16565b6001600160a01b039091166000908152600a6020526040902055509150613bc59050565b859150505b9695505050505050565b6003546001600160a01b0316600083613c6057816001600160a01b03166381a612d6876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015613c2f57600080fd5b505afa158015613c43573d6000803e3d6000fd5b505050506040513d6020811015613c5957600080fd5b5051613cda565b816001600160a01b031663e124e6d2876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015613cad57600080fd5b505afa158015613cc1573d6000803e3d6000fd5b505050506040513d6020811015613cd757600080fd5b50515b90508315613d265782811115613d215760405162461bcd60e51b8152600401808060200182810382526031815260200180614ecc6031913960400191505060405180910390fd5b613d65565b82811015613d655760405162461bcd60e51b8152600401808060200182810382526030815260200180614e2c6030913960400191505060405180910390fd5b613d7086858761489f565b6000826001600160a01b03166312d43a516040518163ffffffff1660e01b815260040160206040518083038186803b158015613dab57600080fd5b505afa158015613dbf573d6000803e3d6000fd5b505050506040513d6020811015613dd557600080fd5b50516004805460408051633cc8e33b60e21b81526001600160a01b038e8116948201949094528c841660248201528b841660448201528915156064820152608481018b905260a48101879052600160c4820152905193945091169163f3238cec9160e48082019260009290919082900301818387803b158015613e5757600080fd5b505af1158015613e6b573d6000803e3d6000fd5b50505050806001600160a01b0316636d63c1d0846040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015613ebe57600080fd5b505af1158015613ed2573d6000803e3d6000fd5b505060055460408051630f8ee8bb60e11b81526001600160a01b038e811660048301528d811660248301528c81166044830152606482018c90528a151560848301529151919092169350631f1dd176925060a480830192600092919082900301818387803b158015613f4357600080fd5b505af1158015613f57573d6000803e3d6000fd5b50505050806001600160a01b031663d3c87bbb846040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b158015613faa57600080fd5b505af1158015613fbe573d6000803e3d6000fd5b50505050613fcc89876142fa565b505050505050505050565b600d546040805163d3bab1d160e01b81526001600160a01b03858116600483015260248201859052915160009384938493849384938493169163d3bab1d191604480830192610120929190829003018186803b15801561403657600080fd5b505afa15801561404a573d6000803e3d6000fd5b505050506040513d61012081101561406157600080fd5b508051602082015160408301516060840151608085015160a090950151939a5091985096509450909250905061409883828461489f565b600d54600160a81b900460ff166140b4575050505050506116c7565b806140c4575050505050506116c7565b60008211614119576040805162461bcd60e51b815260206004820152601d60248201527f506f736974696f6e4d616e616765723a206c6f6e67206465706f736974000000604482015290519081900360640190fd5b60035460408051634a3f088d60e01b81526001600160a01b038b811660048301528781166024830152868116604483015284151560648301529151919092169160009182918491634a3f088d9160848082019261010092909190829003018186803b15801561418757600080fd5b505afa15801561419b573d6000803e3d6000fd5b505050506040513d6101008110156141b257600080fd5b5080516020909101519092509050816141d3575050505050505050506116c7565b60006141df8387614847565b90506000846001600160a01b0316630a48d5a98c8c6040518363ffffffff1660e01b815260040180836001600160a01b031681526020018281526020019250505060206040518083038186803b15801561423857600080fd5b505afa15801561424c573d6000803e3d6000fd5b505050506040513d602081101561426257600080fd5b5051905060006142728483614847565b9050600061428685613b32886127106147af565b905060006142a783613b3260085461271001886147af90919063ffffffff16565b9050818110156142e85760405162461bcd60e51b8152600401808060200182810382526027815260200180614f1d6027913960400191505060405180910390fd5b50505050505050505050505050505050565b6009546001600160a01b03168061431157506116c7565b600080826001600160a01b031663534ef883866040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050604080518083038186803b15801561436057600080fd5b505afa158015614374573d6000803e3d6000fd5b505050506040513d604081101561438a57600080fd5b5080516020918201516003546040805163318bc68960e01b815290519396509194507fc2414023ce7002ee98557d1e7be21e5559073336f2217ee5f9b2e50fd85f71ee93899389936001600160a01b039093169263318bc689926004808301939192829003018186803b15801561332f57600080fd5b6060614455826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316614a579092919063ffffffff16565b8051909150156134815780806020019051602081101561447457600080fd5b50516134815760405162461bcd60e51b815260040180806020018281038252602a815260200180614fb9602a913960400191505060405180910390fd5b60035460408051634998b10960e11b81526001600160a01b03878116600483015286811660248301528481166044830152915160009384931691639331621291606480830192602092919082900301818787803b15801561451157600080fd5b505af1158015614525573d6000803e3d6000fd5b505050506040513d602081101561453b57600080fd5b505190508381101561457e5760405162461bcd60e51b815260040180806020018281038252602b815260200180614da1602b913960400191505060405180910390fd5b95945050505050565b60008261459657506000613bc5565b816145a357506001613bc5565b6000866001885103815181106145b557fe5b602090810291909101015160035460408051634a3f088d60e01b81526001600160a01b038c81166004830152808516602483015289811660448301528815156064830152915193945091169160009182918491634a3f088d91608480830192610100929190829003018186803b15801561462e57600080fd5b505afa158015614642573d6000803e3d6000fd5b505050506040513d61010081101561465957600080fd5b508051602090910151909250905081614679576000945050505050613bc5565b60006146858388614847565b90506000846001600160a01b0316630a48d5a9878d6040518363ffffffff1660e01b815260040180836001600160a01b031681526020018281526020019250505060206040518083038186803b1580156146de57600080fd5b505afa1580156146f2573d6000803e3d6000fd5b505050506040513d602081101561470857600080fd5b5051905060006147188483614847565b9050600061472c85613b32886127106147af565b9050600061474d83613b3260085461271001886147af90919063ffffffff16565b919091109f9e505050505050505050505050505050565b60006147a683836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250614a6e565b90505b92915050565b6000826147be575060006147a9565b828202828482816147cb57fe5b04146147a65760405162461bcd60e51b8152600401808060200182810382526021815260200180614eab6021913960400191505060405180910390fd5b60006147a683836040518060400160405280601a815260200179536166654d6174683a206469766973696f6e206279207a65726f60301b815250614b05565b6000828201838110156147a6576040805162461bcd60e51b815260206004820152601b60248201527a536166654d6174683a206164646974696f6e206f766572666c6f7760281b604482015290519081900360640190fd5b806148a957613481565b811561499c576001600160a01b0383166000908152600b6020526040902054801580159061495a57506003546040805163783a2b6760e11b81526001600160a01b0387811660048301529151849361495893879391169163f07456ce91602480820192602092909190829003018186803b15801561492657600080fd5b505afa15801561493a573d6000803e3d6000fd5b505050506040513d602081101561495057600080fd5b505190614847565b115b156149965760405162461bcd60e51b815260040180806020018281038252602e815260200180614d33602e913960400191505060405180910390fd5b50613481565b6001600160a01b0383166000908152600c60205260409020548015801590614a1557506003546040805163114f1b5560e31b81526001600160a01b03878116600483015291518493614a13938793911691638a78daa891602480820192602092909190829003018186803b15801561492657600080fd5b115b15614a515760405162461bcd60e51b815260040180806020018281038252602f815260200180614e7c602f913960400191505060405180910390fd5b50505050565b6060614a668484600085614b6a565b949350505050565b60008184841115614afd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015614ac2578181015183820152602001614aaa565b50505050905090810190601f168015614aef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b60008183614b545760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315614ac2578181015183820152602001614aaa565b506000838581614b6057fe5b0495945050505050565b606082471015614bab5760405162461bcd60e51b8152600401808060200182810382526026815260200180614e066026913960400191505060405180910390fd5b614bb485614cc6565b614c05576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b60208310614c445780518252601f199092019160209182019101614c25565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114614ca6576040519150601f19603f3d011682016040523d82523d6000602084013e614cab565b606091505b5091509150614cbb828286614ccc565b979650505050505050565b3b151590565b60608315614cdb5750816139ef565b825115614ceb5782518084602001fd5b60405162461bcd60e51b8152602060048201818152845160248401528451859391928392604401919085019080838360008315614ac2578181015183820152602001614aaa56fe42617365506f736974696f6e4d616e616765723a206d617820676c6f62616c206c6f6e67732065786365656465645265656e7472616e637947756172643a207265656e7472616e742063616c6c00476f7665726e61626c653a20666f7262696464656e000000000000000000000042617365506f736974696f6e4d616e616765723a20696e73756666696369656e7420616d6f756e744f7574416464726573733a20756e61626c6520746f2073656e642076616c75652c20726563697069656e74206d61792068617665207265766572746564416464726573733a20696e73756666696369656e742062616c616e636520666f722063616c6c42617365506f736974696f6e4d616e616765723a206d61726b207072696365206c6f776572207468616e206c696d697442617365506f736974696f6e4d616e616765723a20666f7262696464656e000042617365506f736974696f6e4d616e616765723a206d617820676c6f62616c2073686f727473206578636565646564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7742617365506f736974696f6e4d616e616765723a206d61726b20707269636520686967686572207468616e206c696d6974506f736974696f6e4d616e616765723a20666f7262696464656e000000000000506f736974696f6e4d616e616765723a206c6f6e67206c6576657261676520646563726561736542617365506f736974696f6e4d616e616765723a20696e76616c6964205f706174682e6c656e677468506f736974696f6e4d616e616765723a20696e76616c6964205f636f6c6c61746572616c546f6b656e42617365506f736974696f6e4d616e616765723a20696e76616c69642073656e6465725361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564506f736974696f6e4d616e616765723a20696e76616c6964205f706174682e6c656e677468a2646970667358221220d46b9214685488ef5208db15114ce1f5b375887b041ec6561b9271132a6bfb4664736f6c634300060c0033