file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity ^0.4.11; import './SmartTokenController.sol'; import './Managed.sol'; import './Utils.sol'; import './interfaces/ITokenChanger.sol'; import './interfaces/ISmartToken.sol'; import './interfaces/IBancorFormula.sol'; /* Open issues: - Add miner front-running attack protection. The issue is somewhat mitigated by the use of _minReturn when changing - Possibly add getters for reserve fields so that the client won't need to rely on the order in the struct */ /* Bancor Changer v0.2 The Bancor version of the token changer, allows changing between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves. ERC20 reserve token balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on the actual reserve balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract. The changer is upgradable (just like any SmartTokenController). WARNING: It is NOT RECOMMENDED to use the changer with Smart Tokens that have less than 8 decimal digits or with very small numbers because of precision loss */ contract BancorChanger is ITokenChanger, SmartTokenController, Managed { struct Reserve { uint256 virtualBalance; // virtual balance uint8 ratio; // constant reserve ratio (CRR), 1-100 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isPurchaseEnabled; // is purchase of the smart token enabled with the reserve, can be set by the owner bool isSet; // used to tell if the mapping element is defined } string public version = '0.2'; string public changerType = 'bancor'; IBancorFormula public formula; // bancor calculation formula contract address[] public reserveTokens; // ERC20 standard token addresses mapping (address => Reserve) public reserves; // reserve token addresses -> reserve data uint8 private totalReserveRatio = 0; // used to efficiently prevent increasing the total reserve ratio above 100% uint16 public maxChangeFeePercentage = 0; // maximum change fee percentage for the lifetime of the contract, 0...10000 (0 = no fee, 1 = 0.01%, 10000 = 100%) uint16 public changeFeePercentage = 0; // current change fee percentage, 0...maxChangeFeePercentage bool public changingEnabled = true; // true if token changing is enabled, false if not // triggered when a change between two tokens occurs event Change(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return); // triggered when the price between two tokens changes event PriceChange(address indexed _token1, address indexed _token2, uint256 _token1Amount, uint256 _token2Amount); /** @dev constructor @param _token smart token governed by the changer @param _formula address of a bancor formula contract @param _maxChangeFeePercentage maximum change fee percentage */ function BancorChanger(ISmartToken _token, IBancorFormula _formula, uint16 _maxChangeFeePercentage, IERC20Token _reserveToken, uint8 _reserveRatio) SmartTokenController(_token) validAddress(_formula) validMaxChangeFeePercentage(_maxChangeFeePercentage) { formula = _formula; maxChangeFeePercentage = _maxChangeFeePercentage; if (address(_reserveToken) != 0x0) addReserve(_reserveToken, _reserveRatio, false); } // validates a reserve token address - verifies that the address belongs to one of the reserve tokens modifier validReserve(address _address) { require(reserves[_address].isSet); _; } // validates a token address - verifies that the address belongs to one of the changeable tokens modifier validToken(address _address) { require(_address == address(token) || reserves[_address].isSet); _; } // validates maximum change fee percentage modifier validMaxChangeFeePercentage(uint16 _changeFeePercentage) { require(_changeFeePercentage >= 0 && _changeFeePercentage <= 10000); _; } // validates change fee percentage modifier validChangeFeePercentage(uint16 _changeFeePercentage) { require(_changeFeePercentage >= 0 && _changeFeePercentage <= maxChangeFeePercentage); _; } // validates reserve ratio range modifier validReserveRatio(uint8 _ratio) { require(_ratio > 0 && _ratio <= 100); _; } // allows execution only when changing isn't disabled modifier changingAllowed { assert(changingEnabled); _; } /** @dev returns the number of reserve tokens defined @return number of reserve tokens */ function reserveTokenCount() public constant returns (uint16 count) { return uint16(reserveTokens.length); } /** @dev returns the number of changeable tokens supported by the contract note that the number of changeable tokens is the number of reserve token, plus 1 (that represents the smart token) @return number of changeable tokens */ function changeableTokenCount() public constant returns (uint16 count) { return reserveTokenCount() + 1; } /** @dev given a changeable token index, returns the changeable token contract address @param _tokenIndex changeable token index @return number of changeable tokens */ function changeableToken(uint16 _tokenIndex) public constant returns (address tokenAddress) { if (_tokenIndex == 0) return token; return reserveTokens[_tokenIndex - 1]; } /* @dev allows the owner to update the formula contract address @param _formula address of a bancor formula contract */ function setFormula(IBancorFormula _formula) public ownerOnly validAddress(_formula) notThis(_formula) { require(_formula != formula); // validate input formula = _formula; } /** @dev disables the entire change functionality this is a safety mechanism in case of a emergency can only be called by the manager @param _disable true to disable changing, false to re-enable it */ function disableChanging(bool _disable) public managerOnly { changingEnabled = !_disable; } /** @dev updates the current change fee percentage can only be called by the manager @param _changeFeePercentage new change fee percentage */ function setChangeFeePercentage(uint16 _changeFeePercentage) public managerOnly validChangeFeePercentage(_changeFeePercentage) { changeFeePercentage = _changeFeePercentage; } /* @dev returns the change fee for a given return amount @return change fee */ function getChangeFee(uint256 _amount) public constant returns (uint256 fee) { return safeMul(_amount, changeFeePercentage) / 10000; } /** @dev defines a new reserve for the token can only be called by the owner while the changer is inactive @param _token address of the reserve token @param _ratio constant reserve ratio, 1-100 @param _enableVirtualBalance true to enable virtual balance for the reserve, false to disable it */ function addReserve(IERC20Token _token, uint8 _ratio, bool _enableVirtualBalance) public ownerOnly inactive validAddress(_token) notThis(_token) validReserveRatio(_ratio) { require(_token != address(token) && !reserves[_token].isSet && totalReserveRatio + _ratio <= 100); // validate input reserves[_token].virtualBalance = 0; reserves[_token].ratio = _ratio; reserves[_token].isVirtualBalanceEnabled = _enableVirtualBalance; reserves[_token].isPurchaseEnabled = true; reserves[_token].isSet = true; reserveTokens.push(_token); totalReserveRatio += _ratio; } /** @dev updates one of the token reserves can only be called by the owner @param _reserveToken address of the reserve token @param _ratio constant reserve ratio, 1-100 @param _enableVirtualBalance true to enable virtual balance for the reserve, false to disable it @param _virtualBalance new reserve's virtual balance */ function updateReserve(IERC20Token _reserveToken, uint8 _ratio, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validReserve(_reserveToken) validReserveRatio(_ratio) { Reserve reserve = reserves[_reserveToken]; require(totalReserveRatio - reserve.ratio + _ratio <= 100); // validate input totalReserveRatio = totalReserveRatio - reserve.ratio + _ratio; reserve.ratio = _ratio; reserve.isVirtualBalanceEnabled = _enableVirtualBalance; reserve.virtualBalance = _virtualBalance; } /** @dev disables purchasing with the given reserve token in case the reserve token got compromised can only be called by the owner note that selling is still enabled regardless of this flag and it cannot be disabled by the owner @param _reserveToken reserve token contract address @param _disable true to disable the token, false to re-enable it */ function disableReservePurchases(IERC20Token _reserveToken, bool _disable) public ownerOnly validReserve(_reserveToken) { reserves[_reserveToken].isPurchaseEnabled = !_disable; } /** @dev returns the reserve's virtual balance if one is defined, otherwise returns the actual balance @param _reserveToken reserve token contract address @return reserve balance */ function getReserveBalance(IERC20Token _reserveToken) public constant validReserve(_reserveToken) returns (uint256 balance) { Reserve reserve = reserves[_reserveToken]; return reserve.isVirtualBalanceEnabled ? reserve.virtualBalance : _reserveToken.balanceOf(this); } /** @dev returns the expected return for changing a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to change from @param _toToken ERC20 token to change to @param _amount amount to change, in fromToken @return expected change return amount */ function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant validToken(_fromToken) validToken(_toToken) returns (uint256 amount) { require(_fromToken != _toToken); // validate input // change between the token and one of its reserves if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); // change between 2 reserves uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount); return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount)); } /** @dev returns the expected return for buying the token for a reserve token @param _reserveToken reserve token contract address @param _depositAmount amount to deposit (in the reserve token) @return expected purchase return amount */ function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount) public constant active validReserve(_reserveToken) returns (uint256 amount) { Reserve reserve = reserves[_reserveToken]; require(reserve.isPurchaseEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = getReserveBalance(_reserveToken); amount = formula.calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount); if (changeFeePercentage == 0) return amount; uint256 fee = getChangeFee(amount); return safeSub(amount, fee); } /** @dev returns the expected return for selling the token for one of its reserve tokens @param _reserveToken reserve token contract address @param _sellAmount amount to sell (in the smart token) @return expected sale return amount */ function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount) public constant returns (uint256 amount) { return getSaleReturn(_reserveToken, _sellAmount, token.totalSupply()); } /** @dev changes a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to change from @param _toToken ERC20 token to change to @param _amount amount to change, in fromToken @param _minReturn if the change results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return change return amount */ function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public validToken(_fromToken) validToken(_toToken) returns (uint256 amount) { require(_fromToken != _toToken); // validate input // change between the token and one of its reserves if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); // change between 2 reserves uint256 purchaseAmount = buy(_fromToken, _amount, 1); return sell(_toToken, purchaseAmount, _minReturn); } /** @dev buys the token by depositing one of its reserve tokens @param _reserveToken reserve token contract address @param _depositAmount amount to deposit (in the reserve token) @param _minReturn if the change results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return buy return amount */ function buy(IERC20Token _reserveToken, uint256 _depositAmount, uint256 _minReturn) public changingAllowed greaterThanZero(_minReturn) returns (uint256 amount) { amount = getPurchaseReturn(_reserveToken, _depositAmount); assert(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount // update virtual balance if relevant Reserve reserve = reserves[_reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = safeAdd(reserve.virtualBalance, _depositAmount); assert(_reserveToken.transferFrom(msg.sender, this, _depositAmount)); // transfer _depositAmount funds from the caller in the reserve token token.issue(msg.sender, amount); // issue new funds to the caller in the smart token Change(_reserveToken, token, msg.sender, _depositAmount, amount); PriceChange(_reserveToken, token, safeMul(getReserveBalance(_reserveToken), 100), safeMul(token.totalSupply(), reserve.ratio)); return amount; } /** @dev sells the token by withdrawing from one of its reserve tokens @param _reserveToken reserve token contract address @param _sellAmount amount to sell (in the smart token) @param _minReturn if the change results in an amount smaller the minimum return - it is cancelled, must be nonzero @return sell return amount */ function sell(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _minReturn) public changingAllowed greaterThanZero(_minReturn) returns (uint256 amount) { require(_sellAmount <= token.balanceOf(msg.sender)); // validate input amount = getSaleReturn(_reserveToken, _sellAmount); assert(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount uint256 reserveBalance = getReserveBalance(_reserveToken); assert(amount <= reserveBalance); // ensure that the trade won't result in negative reserve uint256 tokenSupply = token.totalSupply(); assert(amount < reserveBalance || _sellAmount == tokenSupply); // ensure that the trade will only deplete the reserve if the total supply is depleted as well // update virtual balance if relevant Reserve reserve = reserves[_reserveToken]; if (reserve.isVirtualBalanceEnabled) reserve.virtualBalance = safeSub(reserve.virtualBalance, amount); token.destroy(msg.sender, _sellAmount); // destroy _sellAmount from the caller's balance in the smart token assert(_reserveToken.transfer(msg.sender, amount)); // transfer funds to the caller in the reserve token // note that it might fail if the actual reserve balance is smaller than the virtual balance Change(token, _reserveToken, msg.sender, _sellAmount, amount); PriceChange(token, _reserveToken, safeMul(token.totalSupply(), reserve.ratio), safeMul(getReserveBalance(_reserveToken), 100)); return amount; } /** @dev utility, returns the expected return for selling the token for one of its reserve tokens, given a total supply override @param _reserveToken reserve token contract address @param _sellAmount amount to sell (in the smart token) @param _totalSupply total token supply, overrides the actual token total supply when calculating the return @return sale return amount */ function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _totalSupply) private constant active validReserve(_reserveToken) greaterThanZero(_totalSupply) returns (uint256 amount) { Reserve reserve = reserves[_reserveToken]; uint256 reserveBalance = getReserveBalance(_reserveToken); amount = formula.calculateSaleReturn(_totalSupply, reserveBalance, reserve.ratio, _sellAmount); if (changeFeePercentage == 0) return amount; uint256 fee = getChangeFee(amount); return safeSub(amount, fee); } }
reserve token addresses -> reserve data
mapping (address => Reserve) public reserves;
2,496,389
[ 1, 455, 6527, 1147, 6138, 317, 20501, 501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 1124, 6527, 13, 1071, 400, 264, 3324, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) public onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; interface IVault { // Events // Log Users Deposit event Deposit(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users withdraw event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users borrow event Borrow(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users debt repay event Payback(address indexed userAddrs, address indexed asset, uint256 amount); // Log New active provider event SetActiveProvider(address providerAddr); // Log Switch providers event Switch( address vault, address fromProviderAddrs, address toProviderAddr, uint256 debtamount, uint256 collattamount ); // Core Vault Functions function deposit(uint256 _collateralAmount) external payable; function withdraw(int256 _withdrawAmount) external; function borrow(uint256 _borrowAmount) external; function payback(int256 _repayAmount) external payable; function executeSwitch( address _newProvider, uint256 _flashLoanDebt, uint256 _fee ) external; //Getter Functions function activeProvider() external view returns (address); function borrowBalance(address _provider) external view returns (uint256); function depositBalance(address _provider) external view returns (uint256); function getNeededCollateralFor(uint256 _amount, bool _withFactors) external view returns (uint256); function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256); function getProviders() external view returns (address[] memory); function fujiERC1155() external view returns (address); //Setter Functions function setActiveProvider(address _provider) external; function updateF1155Balances() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; contract VaultControl is Ownable, Pausable { using SafeMath for uint256; using UniERC20 for IERC20; //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } //Vault Struct for Managed Assets VaultAssets public vAssets; //Pause Functions /** * @dev Emergency Call to stop all basic money flow functions. */ function pause() public onlyOwner { _pause(); } /** * @dev Emergency Call to stop all basic money flow functions. */ function unpause() public onlyOwner { _pause(); } } contract VaultBase is VaultControl { // Internal functions /** * @dev Executes deposit operation with delegatecall. * @param _amount: amount to be deposited * @param _provider: address of provider to be used */ function _deposit(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes withdraw operation with delegatecall. * @param _amount: amount to be withdrawn * @param _provider: address of provider to be used */ function _withdraw(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes borrow operation with delegatecall. * @param _amount: amount to be borrowed * @param _provider: address of provider to be used */ function _borrow(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Executes payback operation with delegatecall. * @param _amount: amount to be paid back * @param _provider: address of provider to be used */ function _payback(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Returns byte response of delegatcalls */ function _execute(address _target, bytes memory _data) internal whenNotPaused returns (bytes memory response) { /* solhint-disable */ assembly { let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0) let size := returndatasize() response := mload(0x40) mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } /* solhint-disable */ } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IFujiAdmin { function validVault(address _vaultAddr) external view returns (bool); function getFlasher() external view returns (address); function getFliquidator() external view returns (address); function getController() external view returns (address); function getTreasury() external view returns (address payable); function getaWhiteList() external view returns (address); function getVaultHarvester() external view returns (address); function getBonusFlashL() external view returns (uint64, uint64); function getBonusLiq() external view returns (uint64, uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; interface IFujiERC1155 { //Asset Types enum AssetType { //uint8 = 0 collateralToken, //uint8 = 1 debtToken } //General Getter Functions function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256); function qtyOfManagedAssets() external view returns (uint64); function balanceOf(address _account, uint256 _id) external view returns (uint256); //function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256); //function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256); //Permit Controlled Functions function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external; function burn( address _account, uint256 _id, uint256 _amount ) external; function updateState(uint256 _assetID, uint256 _newBalance) external; function addInitializeAsset(AssetType _type, address _addr) external returns (uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; interface IProvider { //Basic Core Functions function deposit(address _collateralAsset, uint256 _collateralAmount) external payable; function borrow(address _borrowAsset, uint256 _borrowAmount) external payable; function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable; function payback(address _borrowAsset, uint256 _borrowAmount) external payable; // returns the borrow annualized rate for an asset in ray (1e27) //Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24) function getBorrowRateFor(address _asset) external view returns (uint256); function getBorrowBalance(address _asset) external view returns (uint256); function getDepositBalance(address _asset) external view returns (uint256); function getBorrowBalanceOf(address _asset, address _who) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IAlphaWhiteList { function whiteListRoutine( address _usrAddrs, uint64 _assetId, uint256 _amount, address _erc1155 ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity <0.8.0; /** * @title Errors library * @author Fuji * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = Validation Logic 100 series * - MATH = Math libraries 200 series * - RF = Refinancing 300 series * - VLT = vault 400 series * - SP = Special 900 series */ library Errors { //Errors string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match. string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155 string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract. string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid. string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer. string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved. string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27) string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close. string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest. string public constant VL_HARVESTING_FAILED = "126"; // Harvesting Function failed, check provided _farmProtocolNum or no claimable balance. string public constant VL_FLASHLOAN_FAILED = "127"; // Flashloan failed string public constant MATH_DIVISION_BY_ZERO = "201"; string public constant MATH_ADDITION_OVERFLOW = "202"; string public constant MATH_MULTIPLICATION_OVERFLOW = "203"; string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0 string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library UniERC20 { using SafeERC20 for IERC20; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function uniTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { to.transfer(amount); } else { token.safeTransfer(to, amount); } } } function uniApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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.4._ */ 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.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = (_flashLoanAmount).mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of USDC in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into balances across all providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface LQTYInterface {} contract LQTYHelpers { function _initializeTrouve() internal { //TODO function } } contract ProviderLQTY is IProvider, LQTYHelpers { using SafeMath for uint256; using UniERC20 for IERC20; function deposit(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function borrow(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function withdraw(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function payback(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function getBorrowRateFor(address asset) external view override returns (uint256) { asset; //TODO return 0; } function getBorrowBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { _asset; _who; //TODO return 0; } function getDepositBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IGenCyToken is IERC20 { function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); } interface IWeth is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } interface ICyErc20 is IGenCyToken { function mint(uint256) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); } interface IComptroller { function markets(address) external returns (bool, uint256); function enterMarkets(address[] calldata) external returns (uint256[] memory); function exitMarket(address cyTokenAddress) external returns (uint256); function getAccountLiquidity(address) external view returns ( uint256, uint256, uint256 ); } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract HelperFunct { function _isETH(address token) internal pure returns (bool) { return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); } function _getMappingAddr() internal pure returns (address) { return 0x17525aFdb24D24ABfF18108E7319b93012f3AD24; } function _getComptrollerAddress() internal pure returns (address) { return 0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB; } //IronBank functions /** * @dev Approves vault's assets as collateral for IronBank Protocol. * @param _cyTokenAddress: asset type to be approved as collateral. */ function _enterCollatMarket(address _cyTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); address[] memory cyTokenMarkets = new address[](1); cyTokenMarkets[0] = _cyTokenAddress; comptroller.enterMarkets(cyTokenMarkets); } /** * @dev Removes vault's assets as collateral for IronBank Protocol. * @param _cyTokenAddress: asset type to be removed as collateral. */ function _exitCollatMarket(address _cyTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); comptroller.exitMarket(_cyTokenAddress); } } contract ProviderIronBank is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Enter and/or ensure collateral market is enacted _enterCollatMarket(cyTokenAddr); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }(); _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the cyToken contract ICyErc20 cyToken = ICyErc20(cyTokenAddr); //Checks, Vault balance of ERC20 to make deposit require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance"); //Approve to move ERC20tokens erc20token.uniApprove(address(cyTokenAddr), _amount); // IronBank Protocol mints cyTokens, trhow error if not require(cyToken.mint(_amount) == 0, "Deposit-failed"); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cyToken contract IGenCyToken cyToken = IGenCyToken(cyTokenAddr); //IronBank Protocol Redeem Process, throw errow if not. require(cyToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).withdraw(_amount); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cyToken contract IGenCyToken cyToken = IGenCyToken(cyTokenAddr); //Enter and/or ensure collateral market is enacted //_enterCollatMarket(cyTokenAddr); //IronBank Protocol Borrow Process, throw errow if not. require(cyToken.borrow(_amount) == 0, "borrow-failed"); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { //Get cyToken address from mapping address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); if (_isETH(_asset)) { // Transform ETH to WETH IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }(); _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the corresponding cyToken contract ICyErc20 cyToken = ICyErc20(cyTokenAddr); // Check there is enough balance to pay require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token"); erc20token.uniApprove(address(cyTokenAddr), _amount); cyToken.repayBorrow(_amount); } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18 uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9); // The approximate number of blocks per year that is assumed by the IronBank interest rate model uint256 blocksperYear = 2102400; return bRateperBlock.mul(blocksperYear); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCyToken(cyTokenAddr).borrowBalanceStored(msg.sender); } /** * @dev Return borrow balance of ETH/ERC20_Token. * This function is the accurate way to get IronBank borrow balance. * It costs ~84K gas and is not a view function. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCyToken(cyTokenAddr).borrowBalanceCurrent(_who); } /** * @dev Returns the deposit balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); uint256 cyTokenBal = IGenCyToken(cyTokenAddr).balanceOf(msg.sender); uint256 exRate = IGenCyToken(cyTokenAddr).exchangeRateStored(); return exRate.mul(cyTokenBal).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IWethERC20 is IERC20 { function deposit() external payable; function withdraw(uint256) external; } interface SoloMarginContract { struct Info { address owner; uint256 number; } struct Price { uint256 value; } struct Value { uint256 value; } struct Rate { uint256 value; } enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call } enum AssetDenomination { Wei, Par } enum AssetReference { Delta, Target } struct AssetAmount { bool sign; AssetDenomination denomination; AssetReference ref; uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct Wei { bool sign; uint256 value; } function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external; function getAccountWei(Info calldata _account, uint256 _marketId) external view returns (Wei memory); function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 _marketId) external view returns (address); function getAccountValues(Info memory _account) external view returns (Value memory, Value memory); function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory); } contract HelperFunct { /** * @dev get Dydx Solo Address */ function getDydxAddress() public pure returns (address addr) { addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; } /** * @dev get WETH address */ function getWETHAddr() public pure returns (address weth) { weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } /** * @dev Return ethereum address */ function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } /** * @dev Get Dydx Market ID from token Address */ function _getMarketId(SoloMarginContract _solo, address _token) internal view returns (uint256 _marketId) { uint256 markets = _solo.getNumMarkets(); address token = _token == _getEthAddr() ? getWETHAddr() : _token; bool check = false; for (uint256 i = 0; i < markets; i++) { if (token == _solo.getMarketTokenAddress(i)) { _marketId = i; check = true; break; } } require(check, "DYDX Market doesnt exist!"); } /** * @dev Get Dydx Acccount arg */ function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) { SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1); accounts[0] = (SoloMarginContract.Info(address(this), 0)); return accounts; } /** * @dev Get Dydx Actions args. */ function _getActionsArgs( uint256 _marketId, uint256 _amt, bool _sign ) internal view returns (SoloMarginContract.ActionArgs[] memory) { SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1); SoloMarginContract.AssetAmount memory amount = SoloMarginContract.AssetAmount( _sign, SoloMarginContract.AssetDenomination.Wei, SoloMarginContract.AssetReference.Delta, _amt ); bytes memory empty; SoloMarginContract.ActionType action = _sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw; actions[0] = SoloMarginContract.ActionArgs( action, 0, amount, _marketId, 0, address(this), 0, empty ); return actions; } } contract ProviderDYDX is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; bool public donothing = true; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(tweth), _amount); tweth.withdraw(_amount); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(_asset), _amount); tweth.withdraw(_amount); } } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId); return (_rate.value).mul(1e9).mul(365 days); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. * @param _who: address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IGenCToken is IERC20 { function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); } interface ICErc20 is IGenCToken { function mint(uint256) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); } interface ICEth is IGenCToken { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; } interface IComptroller { function markets(address) external returns (bool, uint256); function enterMarkets(address[] calldata) external returns (uint256[] memory); function exitMarket(address cTokenAddress) external returns (uint256); function getAccountLiquidity(address) external view returns ( uint256, uint256, uint256 ); } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract HelperFunct { function _isETH(address token) internal pure returns (bool) { return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); } function _getMappingAddr() internal pure returns (address) { return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b; } function _getComptrollerAddress() internal pure returns (address) { return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } //Compound functions /** * @dev Approves vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be approved as collateral. */ function _enterCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); address[] memory cTokenMarkets = new address[](1); cTokenMarkets[0] = _cTokenAddress; comptroller.enterMarkets(cTokenMarkets); } /** * @dev Removes vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be removed as collateral. */ function _exitCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); comptroller.exitMarket(_cTokenAddress); } } contract ProviderCompound is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Enter and/or ensure collateral market is enacted _enterCollatMarket(cTokenAddr); if (_isETH(_asset)) { // Create a reference to the cToken contract ICEth cToken = ICEth(cTokenAddr); //Compound protocol Mints cTokens, ETH method cToken.mint{ value: _amount }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the cToken contract ICErc20 cToken = ICErc20(cTokenAddr); //Checks, Vault balance of ERC20 to make deposit require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance"); //Approve to move ERC20tokens erc20token.uniApprove(address(cTokenAddr), _amount); // Compound Protocol mints cTokens, trhow error if not require(cToken.mint(_amount) == 0, "Deposit-failed"); } } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Compound Protocol Redeem Process, throw errow if not. require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Enter and/or ensure collateral market is enacted //_enterCollatMarket(cTokenAddr); //Compound Protocol Borrow Process, throw errow if not. require(cToken.borrow(_amount) == 0, "borrow-failed"); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); if (_isETH(_asset)) { // Create a reference to the corresponding cToken contract ICEth cToken = ICEth(cTokenAddr); cToken.repayBorrow{ value: msg.value }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the corresponding cToken contract ICErc20 cToken = ICErc20(cTokenAddr); // Check there is enough balance to pay require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token"); erc20token.uniApprove(address(cTokenAddr), _amount); cToken.repayBorrow(_amount); } } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18 uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9); // The approximate number of blocks per year that is assumed by the Compound interest rate model uint256 blocksperYear = 2102400; return bRateperBlock.mul(blocksperYear); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender); } /** * @dev Return borrow balance of ETH/ERC20_Token. * This function is the accurate way to get Compound borrow balance. * It costs ~84K gas and is not a view function. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who); } /** * @dev Returns the deposit balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender); uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored(); return exRate.mul(cTokenBal).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface ITokenInterface { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function decimals() external view returns (uint256); } interface IAaveInterface { function deposit( address _asset, uint256 _amount, address _onBehalfOf, uint16 _referralCode ) external; function withdraw( address _asset, uint256 _amount, address _to ) external; function borrow( address _asset, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) external; function repay( address _asset, uint256 _amount, uint256 _rateMode, address _onBehalfOf ) external; function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external; } interface AaveLendingPoolProviderInterface { function getLendingPool() external view returns (address); } interface AaveDataProviderInterface { function getReserveTokensAddresses(address _asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getUserReserveData(address _asset, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveData(address _asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); } interface AaveAddressProviderRegistryInterface { function getAddressesProvidersList() external view returns (address[] memory); } contract ProviderAave is IProvider { using SafeMath for uint256; using UniERC20 for IERC20; function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) { return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet } function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) { return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet } function _getWethAddr() internal pure returns (address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address } function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } function _getIsColl( AaveDataProviderInterface _aaveData, address _token, address _user ) internal view returns (bool isCol) { (, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user); } function _convertEthToWeth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) _token.deposit{ value: _amount }(); } function _convertWethToEth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) { _token.approve(address(_token), _amount); _token.withdraw(_amount); } } /** * @dev Return the borrowing rate of ETH/ERC20_Token. * @param _asset to query the borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); (, , , , uint256 variableBorrowRate, , , , , ) = AaveDataProviderInterface(aaveData).getReserveData( _asset == _getEthAddr() ? _getWethAddr() : _asset ); return variableBorrowRate; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return variableDebt; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who); return variableDebt; } /** * @dev Return deposit balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return atokenBal; } /** * @dev Deposit ETH/ERC20_Token. * @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); if (isEth) { _amount = _amount == uint256(-1) ? address(this).balance : _amount; _convertEthToWeth(isEth, tokenContract, _amount); } else { _amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount; } tokenContract.approve(address(aave), _amount); aave.deposit(_token, _amount, address(this), 0); if (!_getIsColl(aaveData, _token, address(this))) { aave.setUserUseReserveAsCollateral(_token, true); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; aave.borrow(_token, _amount, 2, 0, address(this)); _convertWethToEth(isEth, ITokenInterface(_token), _amount); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset token address to withdraw. * @param _amount token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); uint256 initialBal = tokenContract.balanceOf(address(this)); aave.withdraw(_token, _amount, address(this)); uint256 finalBal = tokenContract.balanceOf(address(this)); _amount = finalBal.sub(initialBal); _convertWethToEth(isEth, tokenContract, _amount); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback. * @param _amount token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this)); _amount = _amount == uint256(-1) ? variableDebt : _amount; if (isEth) _convertEthToWeth(isEth, tokenContract, _amount); tokenContract.approve(address(aave), _amount); aave.repay(_token, _amount, 2, address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { WadRayMath } from "./WadRayMath.sol"; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant _SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solhint-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solhint-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / _SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solhint-disable-next-line return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { Errors } from "./Errors.sol"; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant _WAD = 1e18; uint256 internal constant _HALF_WAD = _WAD / 2; uint256 internal constant _RAY = 1e27; uint256 internal constant _HALF_RAY = _RAY / 2; uint256 internal constant _WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return _RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return _WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return _HALF_RAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return _HALF_WAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_WAD) / _WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_RAY) / _RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = _WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / _WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * _WAD_RAY_RATIO; require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IFujiERC1155 } from "./IFujiERC1155.sol"; import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { WadRayMath } from "../Libraries/WadRayMath.sol"; import { MathUtils } from "../Libraries/MathUtils.sol"; import { Errors } from "../Libraries/Errors.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; contract F1155Manager is Ownable { using Address for address; // Controls for Mint-Burn Operations mapping(address => bool) public addrPermit; modifier onlyPermit() { require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } function setPermit(address _address, bool _permit) public onlyOwner { require((_address).isContract(), Errors.VL_NOT_A_CONTRACT); addrPermit[_address] = _permit; } } contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager { using WadRayMath for uint256; //FujiERC1155 Asset ID Mapping //AssetType => asset reference address => ERC1155 Asset ID mapping(AssetType => mapping(address => uint256)) public assetIDs; //Control mapping that returns the AssetType of an AssetID mapping(uint256 => AssetType) public assetIDtype; uint64 public override qtyOfManagedAssets; //Asset ID Liquidity Index mapping //AssetId => Liquidity index for asset ID mapping(uint256 => uint256) public indexes; // Optimizer Fee expressed in Ray, where 1 ray = 100% APR //uint256 public optimizerFee; //uint256 public lastUpdateTimestamp; //uint256 public fujiIndex; /// @dev Ignoring leap years //uint256 internal constant SECONDS_PER_YEAR = 365 days; constructor() public { //fujiIndex = WadRayMath.ray(); //optimizerFee = 1e24; } /** * @dev Updates Index of AssetID * @param _assetID: ERC1155 ID of the asset which state will be updated. * @param newBalance: Amount **/ function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance.sub(total); uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio.add(WadRayMath.ray()); result = result.rayMul(indexes[_assetID]); require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128(result); // TODO: calculate interest rate for a fujiOptimizer Fee. /* if(lastUpdateTimestamp==0){ lastUpdateTimestamp = block.timestamp; } uint256 accrued = _calculateCompoundedInterest( optimizerFee, lastUpdateTimestamp, block.timestamp ).rayMul(fujiIndex); fujiIndex = accrued; lastUpdateTimestamp = block.timestamp; */ } } /** * @dev Returns the total supply of Asset_ID with accrued interest. * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function totalSupply(uint256 _assetID) public view virtual override returns (uint256) { // TODO: include interest accrued by Fuji OptimizerFee return super.totalSupply(_assetID).rayMul(indexes[_assetID]); } /** * @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index) * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) { return super.totalSupply(_assetID); } /** * @dev Returns the principal + accrued interest balance of the user * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function balanceOf(address _account, uint256 _assetID) public view override(FujiBaseERC1155, IFujiERC1155) returns (uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return 0; } // TODO: include interest accrued by Fuji OptimizerFee return scaledBalance.rayMul(indexes[_assetID]); } /** * @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ /* function splitBalanceOf( address _account, uint256 _assetID ) public view override returns (uint256,uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return (0,0); } else { TO DO COMPUTATION return (baseprotocol, fuji); } } */ /** * @dev Returns Scaled Balance of the user (e.g. balance/index) * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledBalanceOf(address _account, uint256 _assetID) public view virtual returns (uint256) { return super.balanceOf(_account, _assetID); } /** * @dev Returns the sum of balance of the user for an AssetType. * This function is used for when AssetType have units of account of the same value (e.g stablecoins) * @param _account: address of the User * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset **/ /* function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) { uint256[] memory IDs = engagedIDsOf(_account, _type); for(uint i; i < IDs.length; i++ ){ total = total.add(balanceOf(_account, IDs[i])); } } */ /** * @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol * Emits a {TransferSingle} event. * Requirements: * - `_account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. * - `_amount` should be in WAD */ function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_id][_account] = accountBalance.add(amountScaled); _totalSupply[_id] = assetTotalBalance.add(amountScaled); emit TransferSingle(operator, address(0), _account, _id, _amount); _doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data); } /** * @dev [Batched] version of {mint}. * Requirements: * - `_ids` and `_amounts` must have the same length. * - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function mintBatch( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) external onlyPermit { require(_to != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { accountBalance = _balances[_ids[i]][_to]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_ids[i]][_to] = accountBalance.add(amountScaled); _totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled); } emit TransferBatch(operator, address(0), _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data); } /** * @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol * Requirements: * - `account` cannot be the zero address. * - `account` must have at least `_amount` tokens of token type `_id`. * - `_amount` should be in WAD */ function burn( address _account, uint256 _id, uint256 _amount ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_id][_account] = accountBalance.sub(amountScaled); _totalSupply[_id] = assetTotalBalance.sub(amountScaled); emit TransferSingle(operator, _account, address(0), _id, _amount); } /** * @dev [Batched] version of {burn}. * Requirements: * - `_ids` and `_amounts` must have the same length. */ function burnBatch( address _account, uint256[] memory _ids, uint256[] memory _amounts ) external onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { uint256 amount = _amounts[i]; accountBalance = _balances[_ids[i]][_account]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_ids[i]][_account] = accountBalance.sub(amount); _totalSupply[_ids[i]] = assetTotalBalance.sub(amount); } emit TransferBatch(operator, _account, address(0), _ids, _amounts); } //Getter Functions /** * @dev Getter Function for the Asset ID locally managed * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) { id = assetIDs[_type][_addr]; require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155); } //Setter Functions /** * @dev Sets the FujiProtocol Fee to be charged * @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR) */ /* function setoptimizerFee(uint256 _fee) public onlyOwner { require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL); optimizerFee = _fee; } */ /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI(string memory _newUri) public onlyOwner { _uri = _newUri; } /** * @dev Adds and initializes liquidity index of a new asset in FujiERC1155 * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function addInitializeAsset(AssetType _type, address _addr) external override onlyPermit returns (uint64) { require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS); assetIDs[_type][_addr] = qtyOfManagedAssets; assetIDtype[qtyOfManagedAssets] = _type; //Initialize the liquidity Index indexes[qtyOfManagedAssets] = WadRayMath.ray(); qtyOfManagedAssets++; return qtyOfManagedAssets - 1; } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param _rate The interest rate, in ray * @param _lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ /* function _calculateCompoundedInterest( uint256 _rate, uint256 _lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = _rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } */ } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol"; import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Context } from "@openzeppelin/contracts/utils/Context.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Errors } from "../Libraries/Errors.sol"; /** * * @dev Implementation of the Base ERC1155 multi-token standard functions * for Fuji Protocol control of User collaterals and borrow debt positions. * Originally based on Openzeppelin * */ contract FujiBaseERC1155 is IERC1155, ERC165, Context { using Address for address; using SafeMath for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Mapping from token ID to totalSupply mapping(uint256 => uint256) internal _totalSupply; //Fuji ERC1155 Transfer Control bool public transfersActive; modifier isTransferActive() { require(transfersActive, Errors.VL_NOT_AUTHORIZED); _; } //URI for all token types by relying on ID substitution //https://token.fujiDao.org/{id}.json string internal _uri; /** * @return The total supply of a token id **/ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * Requirements: * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), Errors.VL_ZERO_ADDR_1155); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * Requirements: * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view override returns (uint256[] memory) { require(accounts.length == ids.length, Errors.VL_INPUT_ERROR); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, Errors.VL_INPUT_ERROR); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override isTransferActive { require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data ); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override isTransferActive { require(ids.length == amounts.length, Errors.VL_INPUT_ERROR); require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IVault } from "./Vaults/IVault.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Errors } from "./Libraries/Errors.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { LibUniversalERC20 } from "./Libraries/LibUniversalERC20.sol"; import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } interface IFujiERC1155Ext is IFujiERC1155 { function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); } contract Fliquidator is Ownable, ReentrancyGuard { using SafeMath for uint256; using LibUniversalERC20 for IERC20; struct Factor { uint64 a; uint64 b; } // Flash Close Fee Factor Factor public flashCloseF; IFujiAdmin private _fujiAdmin; IUniswapV2Router02 public swapper; // Log Liquidation event Liquidate( address indexed userAddr, address liquidator, address indexed asset, uint256 amount ); // Log FlashClose event FlashClose(address indexed userAddr, address indexed asset, uint256 amount); // Log Liquidation event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount); modifier isAuthorized() { require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } constructor() public { // 1.013 flashCloseF.a = 1013; flashCloseF.b = 1000; } receive() external payable {} // FLiquidator Core Functions /** * @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault) * @param _userAddrs: Address array of users whose position is liquidatable * @param _vault: Address of the vault in where liquidation will occur */ function batchLiquidate(address[] calldata _userAddrs, address _vault) external nonReentrant isValidVault(_vault) { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length); uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length); // Build the required Arrays to query balanceOfBatch from f1155 for (uint256 i = 0; i < _userAddrs.length; i++) { formattedUserAddrs[2 * i] = _userAddrs[i]; formattedUserAddrs[2 * i + 1] = _userAddrs[i]; formattedIds[2 * i] = vAssets.collateralID; formattedIds[2 * i + 1] = vAssets.borrowID; } // Get user Collateral and Debt Balances uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds); uint256 neededCollateral; uint256 debtBalanceTotal; for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { // Compute Amount of Minimum Collateral Required including factors neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true); // Check if User is liquidatable if (usrsBals[i] < neededCollateral) { // If true, add User debt balance to the total balance to be liquidated debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]); } else { // Replace User that is not liquidatable by Zero Address formattedUserAddrs[i] = address(0); formattedUserAddrs[i + 1] = address(0); } } // Check there is at least one user liquidatable require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); // Check Liquidator Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= debtBalanceTotal, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer borrowAsset funds from the Liquidator to Here IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), debtBalanceTotal); // Transfer Amount to Vault IERC20(vAssets.borrowAsset).univTransfer(payable(_vault), debtBalanceTotal); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(debtBalanceTotal)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Compute the Liquidator Bonus bonusL uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(debtBalanceTotal, false); // Compute how much collateral needs to be swapt uint256 globalCollateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus)); // Burn Collateral f1155 tokens for each liquidated user _burnMultiLoop(formattedUserAddrs, usrsBals, IVault(_vault), f1155, vAssets); // Withdraw collateral IVault(_vault).withdraw(int256(globalCollateralInPlay)); // Swap Collateral _swap(vAssets.borrowAsset, debtBalanceTotal.add(globalBonus), globalCollateralInPlay); // Transfer to Liquidator the debtBalance + bonus IERC20(vAssets.borrowAsset).univTransfer(msg.sender, debtBalanceTotal.add(globalBonus)); // Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { if (formattedUserAddrs[i] != address(0)) { f1155.burn(formattedUserAddrs[i], vAssets.borrowID, usrsBals[i + 1]); emit Liquidate(formattedUserAddrs[i], msg.sender, vAssets.borrowAsset, usrsBals[i + 1]); } } } /** * @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender * @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashClose( int256 _amount, address _vault, uint8 _flashnum ) external nonReentrant isValidVault(_vault) { Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Balances uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID); // Check Debt is > zero require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount); uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false); require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR); address[] memory userAddressArray = new address[](1); userAddressArray[0] = msg.sender; FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Close, asset: vAssets.borrowAsset, amount: amount, vault: _vault, newProvider: address(0), userAddrs: userAddressArray, userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Close user's debt position by using a flashloan * @param _userAddr: user addr to be liquidated * @param _vault: Vault address * @param _amount: amount received by Flashloan * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashClose} event. */ function executeFlashClose( address payable _userAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Collateral and Debt Balances uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID); // Get user Collateral + Flash Close Fee to close posisition, for _amount passed uint256 userCollateralInPlay = IVault(_vault) .getNeededCollateralFor(_amount.add(_flashloanFee), false) .mul(flashCloseF.a) .div(flashCloseF.b); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(_amount)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Full close if (_amount == userDebtBalance) { f1155.burn(_userAddr, vAssets.collateralID, userCollateral); // Withdraw Full collateral IVault(_vault).withdraw(int256(userCollateral)); // Send unUsed Collateral to User IERC20(vAssets.collateralAsset).univTransfer( _userAddr, userCollateral.sub(userCollateralInPlay) ); } else { f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay); // Withdraw Collateral in play Only IVault(_vault).withdraw(int256(userCollateralInPlay)); } // Swap Collateral for underlying to repay Flashloan uint256 remaining = _swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay); // Send FlashClose Fee to FujiTreasury IERC20(vAssets.collateralAsset).univTransfer(_fujiAdmin.getTreasury(), remaining); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Burn Debt f1155 tokens f1155.burn(_userAddr, vAssets.borrowID, _amount); emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance); } /** * @dev Initiates a flashloan to liquidate array of undercollaterized debt positions, * gets bonus (bonusFlashL in Vault) * @param _userAddrs: Array of Address whose position is liquidatable * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashBatchLiquidate( address[] calldata _userAddrs, address _vault, uint8 _flashnum ) external isValidVault(_vault) nonReentrant { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155Ext f1155 = IFujiERC1155Ext(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); address[] memory formattedUserAddrs = new address[](2 * _userAddrs.length); uint256[] memory formattedIds = new uint256[](2 * _userAddrs.length); // Build the required Arrays to query balanceOfBatch from f1155 for (uint256 i = 0; i < _userAddrs.length; i++) { formattedUserAddrs[2 * i] = _userAddrs[i]; formattedUserAddrs[2 * i + 1] = _userAddrs[i]; formattedIds[2 * i] = vAssets.collateralID; formattedIds[2 * i + 1] = vAssets.borrowID; } // Get user Collateral and Debt Balances uint256[] memory usrsBals = f1155.balanceOfBatch(formattedUserAddrs, formattedIds); uint256 neededCollateral; uint256 debtBalanceTotal; for (uint256 i = 0; i < formattedUserAddrs.length; i += 2) { // Compute Amount of Minimum Collateral Required including factors neededCollateral = IVault(_vault).getNeededCollateralFor(usrsBals[i + 1], true); // Check if User is liquidatable if (usrsBals[i] < neededCollateral) { // If true, add User debt balance to the total balance to be liquidated debtBalanceTotal = debtBalanceTotal.add(usrsBals[i + 1]); } else { // Replace User that is not liquidatable by Zero Address formattedUserAddrs[i] = address(0); formattedUserAddrs[i + 1] = address(0); } } // Check there is at least one user liquidatable require(debtBalanceTotal > 0, Errors.VL_USER_NOT_LIQUIDATABLE); Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.BatchLiquidate, asset: vAssets.borrowAsset, amount: debtBalanceTotal, vault: _vault, newProvider: address(0), userAddrs: formattedUserAddrs, userBalances: usrsBals, userliquidator: msg.sender, fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Liquidate a debt position by using a flashloan * @param _userAddrs: array **See formattedUserAddrs construction in 'function flashBatchLiquidate' * @param _usrsBals: array **See construction in 'function flashBatchLiquidate' * @param _liquidatorAddr: liquidator address * @param _vault: Vault address * @param _amount: amount of debt to be repaid * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashLiquidate} event. */ function executeFlashBatchLiquidation( address[] calldata _userAddrs, uint256[] calldata _usrsBals, address _liquidatorAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // TODO: Transfer corresponding Debt Amount to Fuji Treasury // Repay BaseProtocol debt to release collateral IVault(_vault).payback(int256(_amount)); // Compute the Liquidator Bonus bonusFlashL uint256 globalBonus = IVault(_vault).getLiquidationBonusFor(_amount, true); // Compute how much collateral needs to be swapt for all liquidated Users uint256 globalCollateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus)); // Burn Collateral f1155 tokens for each liquidated user _burnMultiLoop(_userAddrs, _usrsBals, IVault(_vault), f1155, vAssets); // Withdraw collateral IVault(_vault).withdraw(int256(globalCollateralInPlay)); _swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(globalBonus), globalCollateralInPlay); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).univTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Transfer Bonus bonusFlashL to liquidator, minus FlashloanFee convenience IERC20(vAssets.borrowAsset).univTransfer( payable(_liquidatorAddr), globalBonus.sub(_flashloanFee) ); // Burn Debt f1155 tokens and Emit Liquidation Event for Each Liquidated User for (uint256 i = 0; i < _userAddrs.length; i += 2) { if (_userAddrs[i] != address(0)) { f1155.burn(_userAddrs[i], vAssets.borrowID, _usrsBals[i + 1]); emit FlashLiquidate(_userAddrs[i], _liquidatorAddr, vAssets.borrowAsset, _usrsBals[i + 1]); } } } /** * @dev Swap an amount of underlying * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive * @param _collateralAmount: collateral Amount sent for swap */ function _swap( address _borrowAsset, uint256 _amountToReceive, uint256 _collateralAmount ) internal returns (uint256) { // Swap Collateral Asset to Borrow Asset address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory swapperAmounts = swapper.swapETHForExactTokens{ value: _collateralAmount }( _amountToReceive, path, address(this), // solhint-disable-next-line block.timestamp ); return _collateralAmount.sub(swapperAmounts[0]); } /** * @dev Get exact amount of collateral to be swapt * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive */ function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive) internal view returns (uint256) { address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path); return amounts[0]; } /** * @dev Abstracted function to perform MultBatch Burn of Collateral in Batch Liquidation * checking bonus paid to liquidator by each * See "function executeFlashBatchLiquidation" */ function _burnMultiLoop( address[] memory _userAddrs, uint256[] memory _usrsBals, IVault _vault, IFujiERC1155 _f1155, IVaultExt.VaultAssets memory _vAssets ) internal { uint256 bonusPerUser; uint256 collateralInPlayPerUser; for (uint256 i = 0; i < _userAddrs.length; i += 2) { if (_userAddrs[i] != address(0)) { bonusPerUser = _vault.getLiquidationBonusFor(_usrsBals[i + 1], true); collateralInPlayPerUser = _getCollateralInPlay( _vAssets.borrowAsset, _usrsBals[i + 1].add(bonusPerUser) ); _f1155.burn(_userAddrs[i], _vAssets.collateralID, collateralInPlayPerUser); } } } // Administrative functions /** * @dev Set Factors "a" and "b" for a Struct Factor flashcloseF * For flashCloseF; should be > 1, a/b * @param _newFactorA: A number * @param _newFactorB: A number */ function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized { flashCloseF.a = _newFactorA; flashCloseF.b = _newFactorB; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external isAuthorized { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Changes the Swapper contract address * @param _newSwapper: address of new swapper contract */ function setSwapper(address _newSwapper) external isAuthorized { swapper = IUniswapV2Router02(_newSwapper); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { Errors } from "../Libraries/Errors.sol"; import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol"; import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol"; import { ICTokenFlashloan, ICFlashloanReceiver } from "./CreamFlashLoans.sol"; import { FlashLoan } from "./LibFlashLoan.sol"; import { IVault } from "../Vaults/IVault.sol"; interface IFliquidator { function executeFlashClose( address _userAddr, address _vault, uint256 _amount, uint256 _flashloanfee ) external; function executeFlashBatchLiquidation( address[] calldata _userAddrs, uint256[] calldata _usrsBals, address _liquidatorAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external; } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICFlashloanReceiver, ICallee, Ownable { using SafeMath for uint256; using UniERC20 for IERC20; IFujiAdmin private _fujiAdmin; address private immutable _aaveLendingPool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; address private immutable _dydxSoloMargin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; IFujiMappings private immutable _crMappings = IFujiMappings(0x03BD587Fe413D59A20F32Fc75f31bDE1dD1CD6c9); receive() external payable {} modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == _fujiAdmin.getFliquidator() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Routing Function for Flashloan Provider * @param info: struct information for flashLoan * @param _flashnum: integer identifier of flashloan provider */ function initiateFlashloan(FlashLoan.Info calldata info, uint8 _flashnum) external isAuthorized { if (_flashnum == 0) { _initiateAaveFlashLoan(info); } else if (_flashnum == 1) { _initiateDyDxFlashLoan(info); } else if (_flashnum == 2) { _initiateCreamFlashLoan(info); } } // ===================== DyDx FlashLoan =================================== /** * @dev Initiates a DyDx flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateDyDxFlashLoan(FlashLoan.Info calldata info) internal { ISoloMargin solo = ISoloMargin(_dydxSoloMargin); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, info.amount); // Encode FlashLoan.Info for callFunction operations[1] = _getCallAction(abi.encode(info)); // add fee of 2 wei operations[2] = _getDepositAction(marketId, info.amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(address(this)); solo.operate(accountInfos, operations); } /** * @dev Executes DyDx Flashloan, this operation is required * and called by Solo when sending loaned amount * @param sender: Not used * @param account: Not used */ function callFunction( address sender, Account.Info calldata account, bytes calldata data ) external override { require(msg.sender == _dydxSoloMargin && sender == address(this), Errors.VL_NOT_AUTHORIZED); account; FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info)); //Estimate flashloan payback + premium fee of 2 wei, uint256 amountOwing = info.amount.add(2); // Transfer to Vault the flashloan Amount IERC20(info.asset).uniTransfer(payable(info.vault), info.amount); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, info.amount, 2); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose( info.userAddrs[0], info.vault, info.amount, 2 ); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, info.amount, 2 ); } //Approve DYDXSolo to spend to repay flashloan IERC20(info.asset).approve(_dydxSoloMargin, amountOwing); } // ===================== Aave FlashLoan =================================== /** * @dev Initiates an Aave flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateAaveFlashLoan(FlashLoan.Info calldata info) internal { //Initialize Instance of Aave Lending Pool ILendingPool aaveLp = ILendingPool(_aaveLendingPool); //Passing arguments to construct Aave flashloan -limited to 1 asset type for now. address receiverAddress = address(this); address[] memory assets = new address[](1); assets[0] = address(info.asset); uint256[] memory amounts = new uint256[](1); amounts[0] = info.amount; // 0 = no debt, 1 = stable, 2 = variable uint256[] memory modes = new uint256[](1); //modes[0] = 0; //address onBehalfOf = address(this); //bytes memory params = abi.encode(info); //uint16 referralCode = 0; //Aave Flashloan initiated. aaveLp.flashLoan(receiverAddress, assets, amounts, modes, address(this), abi.encode(info), 0); } /** * @dev Executes Aave Flashloan, this operation is required * and called by Aaveflashloan when sending loaned amount */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == _aaveLendingPool && initiator == address(this), Errors.VL_NOT_AUTHORIZED); FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info)); //Estimate flashloan payback + premium fee, uint256 amountOwing = amounts[0].add(premiums[0]); // Transfer to the vault ERC20 IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, amounts[0], premiums[0]); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose( info.userAddrs[0], info.vault, amounts[0], premiums[0] ); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, amounts[0], premiums[0] ); } //Approve aaveLP to spend to repay flashloan IERC20(assets[0]).uniApprove(payable(_aaveLendingPool), amountOwing); return true; } // ===================== CreamFinance FlashLoan =================================== /** * @dev Initiates an CreamFinance flashloan. * @param info: data to be passed between functions executing flashloan logic */ function _initiateCreamFlashLoan(FlashLoan.Info calldata info) internal { // Get crToken Address for Flashloan Call address crToken = _crMappings.addressMapping(info.asset); // Prepara data for flashloan execution bytes memory params = abi.encode(info); // Initialize Instance of Cream crLendingContract ICTokenFlashloan(crToken).flashLoan(address(this), info.amount, params); } /** * @dev Executes CreamFinance Flashloan, this operation is required * and called by CreamFinanceflashloan when sending loaned amount */ function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external override { // Check Msg. Sender is crToken Lending Contract address crToken = _crMappings.addressMapping(underlying); require(msg.sender == crToken && address(this) == sender, Errors.VL_NOT_AUTHORIZED); require(IERC20(underlying).balanceOf(address(this)) >= amount, Errors.VL_FLASHLOAN_FAILED); FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info)); // Estimate flashloan payback + premium fee, uint256 amountOwing = amount.add(fee); // Transfer to the vault ERC20 IERC20(underlying).uniTransfer(payable(info.vault), amount); // Do task according to CallType if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault).executeSwitch(info.newProvider, amount, fee); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator).executeFlashClose(info.userAddrs[0], info.vault, amount, fee); } else { IFliquidator(info.fliquidator).executeFlashBatchLiquidation( info.userAddrs, info.userBalances, info.userliquidator, info.vault, amount, fee ); } // Transfer flashloan + fee back to crToken Lending Contract IERC20(underlying).uniTransfer(payable(crToken), amountOwing); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; library FlashLoan { /** * @dev Used to determine which vault's function to call post-flashloan: * - Switch for executeSwitch(...) * - Close for executeFlashClose(...) * - Liquidate for executeFlashLiquidation(...) * - BatchLiquidate for executeFlashBatchLiquidation(...) */ enum CallType { Switch, Close, BatchLiquidate } /** * @dev Struct of params to be passed between functions executing flashloan logic * @param asset: Address of asset to be borrowed with flashloan * @param amount: Amount of asset to be borrowed with flashloan * @param vault: Vault's address on which the flashloan logic to be executed * @param newProvider: New provider's address. Used when callType is Switch * @param userAddrs: User's address array Used when callType is BatchLiquidate * @param userBals: Array of user's balances, Used when callType is BatchLiquidate * @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate * @param fliquidator: Fujis Liquidator's address. */ struct Info { CallType callType; address asset; uint256 amount; address vault; address newProvider; address[] userAddrs; uint256[] userBalances; address userliquidator; address fliquidator; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library LibUniversalERC20 { using SafeERC20 for IERC20; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function univBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function univTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { (bool sent, ) = to.call{ value: amount }(""); require(sent, "Failed to send Ether"); } else { token.safeTransfer(to, amount); } } } function univApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); } interface ILendingPool { function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; library Account { enum Status { Normal, Liquid, Vapor } struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } } /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } interface ISoloMargin { function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 marketId) external view returns (address); function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; } contract DyDxFlashloanBase { // -- Internal Helper functions -- // function _getMarketIdFromTokenAddress(ISoloMargin solo, address token) internal view returns (uint256) { uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found"); } function _getAccountInfo(address receiver) internal pure returns (Account.Info memory) { return Account.Info({ owner: receiver, number: 1 }); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; interface ICFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } interface ICTokenFlashloan { function flashLoan( address receiver, uint256 amount, bytes calldata params ) external; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IVault } from "./Vaults/IVault.sol"; import { IProvider } from "./Providers/IProvider.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { Errors } from "./Libraries/Errors.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } contract Controller is Ownable { using SafeMath for uint256; IFujiAdmin private _fujiAdmin; modifier isValidVault(address _vaultAddr) { require(_fujiAdmin.validVault(_vaultAddr), "Invalid vault!"); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Performs a forced refinancing routine * @param _vaultAddr: fuji Vault address * @param _newProvider: new provider address * @param _ratioA: ratio to determine how much of debtposition to move * @param _ratioB: _ratioA/_ratioB <= 1, and > 0 * @param _flashNum: integer identifier of flashloan provider */ function doRefinancing( address _vaultAddr, address _newProvider, uint256 _ratioA, uint256 _ratioB, uint8 _flashNum ) external isValidVault(_vaultAddr) onlyOwner { IVault vault = IVault(_vaultAddr); IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets(); vault.updateF1155Balances(); // Check Vault borrowbalance and apply ratio (consider compound or not) uint256 debtPosition = IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr); uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB); // Check Ratio Input and Vault Balance at ActiveProvider require( debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0, Errors.RF_INVALID_RATIO_VALUES ); //Initiate Flash Loan Struct FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Switch, asset: vAssets.borrowAsset, amount: applyRatiodebtPosition, vault: _vaultAddr, newProvider: _newProvider, userAddrs: new address[](0), userBalances: new uint256[](0), userliquidator: address(0), fliquidator: address(0) }); Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum); IVault(_vaultAddr).setActiveProvider(_newProvider); } }
* @dev Withdraw ETH/ERC20_Token. @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) @param _amount: token amount to withdraw./Get cToken address from mapping Create a reference to the corresponding cToken contractCompound Protocol Redeem Process, throw errow if not.
function withdraw(address _asset, uint256 _amount) external payable override { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); IGenCToken cToken = IGenCToken(cTokenAddr); require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); }
1,311,663
[ 1, 1190, 9446, 512, 2455, 19, 654, 39, 3462, 67, 1345, 18, 225, 389, 9406, 30, 1147, 1758, 358, 598, 9446, 18, 261, 1290, 512, 2455, 30, 374, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 13, 225, 389, 8949, 30, 1147, 3844, 358, 598, 9446, 18, 19, 967, 276, 1345, 1758, 628, 2874, 1788, 279, 2114, 358, 326, 4656, 276, 1345, 6835, 16835, 4547, 868, 24903, 4389, 16, 604, 6445, 492, 309, 486, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 598, 9446, 12, 2867, 389, 9406, 16, 2254, 5034, 389, 8949, 13, 3903, 8843, 429, 3849, 288, 203, 565, 1758, 276, 1345, 3178, 273, 11083, 11501, 77, 7742, 24899, 588, 3233, 3178, 1435, 2934, 2867, 3233, 24899, 9406, 1769, 203, 203, 565, 467, 7642, 1268, 969, 276, 1345, 273, 467, 7642, 1268, 969, 12, 71, 1345, 3178, 1769, 203, 203, 565, 2583, 12, 71, 1345, 18, 266, 24903, 14655, 6291, 24899, 8949, 13, 422, 374, 16, 315, 1190, 9446, 17, 7307, 8863, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount_old The current allowed amount in the `approve()` call /// @param _amount_new The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount_old, uint _amount_new) public returns(bool); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract SNcoin_Token is ERC20Interface, Owned { string public constant symbol = "SNcoin"; string public constant name = "scientificcoin"; uint8 public constant decimals = 18; uint private constant _totalSupply = 100000000 * 10**uint(decimals); mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; struct LimitedBalance { uint8 limitType; uint initial; } mapping(address => LimitedBalance) limited_balances; uint8 public constant limitDefaultType = 0; uint8 public constant limitTeamType = 1; uint8 public constant limitBranchType = 2; uint8 private constant limitTeamIdx = 0; uint8 private constant limitBranchIdx = 1; uint8[limitBranchType] private limits; uint8 private constant limitTeamInitial = 90; uint8 private constant limitBranchInitial = 90; uint8 private constant limitTeamStep = 3; uint8 private constant limitBranchStep = 10; address public controller; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { balances[owner] = _totalSupply; transfersEnabled = true; limits[limitTeamIdx] = limitTeamInitial; limits[limitBranchIdx] = limitBranchInitial; emit Transfer(address(0), owner, _totalSupply); } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function setController(address _newController) public onlyOwner { controller = _newController; } function limitOfTeam() public constant returns (uint8 limit) { return 100 - limits[limitTeamIdx]; } function limitOfBranch() public constant returns (uint8 limit) { return 100 - limits[limitBranchIdx]; } function getLimitTypeOf(address tokenOwner) public constant returns (uint8 limitType) { return limited_balances[tokenOwner].limitType; } function getLimitedBalanceOf(address tokenOwner) public constant returns (uint balance) { if (limited_balances[tokenOwner].limitType > 0) { require(limited_balances[tokenOwner].limitType <= limitBranchType); uint minimumLimit = (limited_balances[tokenOwner].initial * limits[limited_balances[tokenOwner].limitType - 1])/100; require(balances[tokenOwner] >= minimumLimit); return balances[tokenOwner] - minimumLimit; } return balanceOf(tokenOwner); } function incrementLimitTeam() public onlyOwner returns (bool success) { require(transfersEnabled); uint8 previousLimit = limits[limitTeamIdx]; if ( previousLimit - limitTeamStep >= 100) { limits[limitTeamIdx] = 0; } else { limits[limitTeamIdx] = previousLimit - limitTeamStep; } return true; } function incrementLimitBranch() public onlyOwner returns (bool success) { require(transfersEnabled); uint8 previousLimit = limits[limitBranchIdx]; if ( previousLimit - limitBranchStep >= 100) { limits[limitBranchIdx] = 0; } else { limits[limitBranchIdx] = previousLimit - limitBranchStep; } return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address _spender, uint _amount) public returns (bool success) { require(transfersEnabled); // Alerts the token controller of the approve function call if (controller != 0) { require(TokenController(controller).onApprove(msg.sender, _spender, allowed[msg.sender][_spender], _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address _to, uint _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint _amount) public returns (bool success) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; doTransfer(_from, _to, _amount); return true; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferToTeam(address _to, uint _amount) public onlyOwner returns (bool success) { require(transfersEnabled); transferToLimited(msg.sender, _to, _amount, limitTeamType); return true; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferToBranch(address _to, uint _amount) public onlyOwner returns (bool success) { require(transfersEnabled); transferToLimited(msg.sender, _to, _amount, limitBranchType); return true; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferToLimited(address _from, address _to, uint _amount, uint8 _limitType) internal { require((_limitType >= limitTeamType) && (_limitType <= limitBranchType)); require((limited_balances[_to].limitType == 0) || (limited_balances[_to].limitType == _limitType)); doTransfer(_from, _to, _amount); uint previousLimitedBalanceInitial = limited_balances[_to].initial; require(previousLimitedBalanceInitial + _amount >= previousLimitedBalanceInitial); // Check for overflow limited_balances[_to].initial = previousLimitedBalanceInitial + _amount; limited_balances[_to].limitType = _limitType; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balanceOf(_from); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (controller != 0) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens balances[_from] = previousBalanceFrom - _amount; if (limited_balances[_from].limitType > 0) { require(limited_balances[_from].limitType <= limitBranchType); uint minimumLimit = (limited_balances[_from].initial * limits[limited_balances[_from].limitType - 1])/100; require(balances[_from] >= minimumLimit); } // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balanceOf(_to); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow balances[_to] = previousBalanceTo + _amount; // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyOwner { transfersEnabled = _transfersEnabled; } /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { if (_token == 0x0) { owner.transfer(address(this).balance); return; } ERC20Interface token = ERC20Interface(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); }
@dev The token controller contract must implement these functions
contract TokenController { function onTransfer(address _from, address _to, uint _amount) public returns(bool); function onApprove(address _owner, address _spender, uint _amount_old, uint _amount_new) public returns(bool); }
5,507,291
[ 1, 1986, 1147, 2596, 6835, 1297, 2348, 4259, 4186, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 2933, 288, 203, 565, 445, 603, 5912, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 8949, 13, 1071, 1135, 12, 6430, 1769, 203, 203, 565, 445, 603, 12053, 537, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 16, 2254, 389, 8949, 67, 1673, 16, 2254, 389, 8949, 67, 2704, 13, 1071, 1135, 12, 6430, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract BasicAccessControl { address public owner; address[] moderatorsArray; uint16 public totalModerators = 0; mapping (address => bool) moderators; bool public isMaintaining = true; constructor() public { owner = msg.sender; AddModerator(msg.sender); } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyModerators() { require(moderators[msg.sender] == true); _; } modifier isActive { require(!isMaintaining); _; } function findInArray(address _address) internal view returns(uint8) { uint8 i = 0; while (moderatorsArray[i] != _address) { i++; } return i; } function ChangeOwner(address _newOwner) onlyOwner public { if (_newOwner != address(0)) { owner = _newOwner; } } function AddModerator(address _newModerator) onlyOwner public { if (moderators[_newModerator] == false) { moderators[_newModerator] = true; moderatorsArray.push(_newModerator); totalModerators += 1; } } function getModerators() public view returns(address[] memory) { return moderatorsArray; } function RemoveModerator(address _oldModerator) onlyOwner public { if (moderators[_oldModerator] == true) { moderators[_oldModerator] = false; uint8 i = findInArray(_oldModerator); while (i<moderatorsArray.length-1) { moderatorsArray[i] = moderatorsArray[i+1]; i++; } moderatorsArray.length--; totalModerators -= 1; } } function UpdateMaintaining(bool _isMaintaining) onlyOwner public { isMaintaining = _isMaintaining; } function isModerator(address _address) public view returns(bool, address) { return (moderators[_address], _address); } } contract randomRange { function getRandom(uint256 minRan, uint256 maxRan, uint8 index, address priAddress) view internal returns(uint) { uint256 genNum = uint256(blockhash(block.number-1)) + uint256(priAddress) + uint256(keccak256(abi.encodePacked(block.timestamp, index))); for (uint8 i = 0; i < index && i < 6; i ++) { genNum /= 256; } return uint(genNum % (maxRan + 1 - minRan) + minRan); } } /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } /// @title Contract for Chainbreakers Items (ERC721Token) /// @author Tobias Thiele - Qwellcode GmbH - www.qwellcode.de /* HOSTFILE * 0 = 3D Model (*.glb) * 1 = Icon * 2 = Thumbnail * 3 = Transparent */ /* RARITY * 0 = Common * 1 = Uncommon * 2 = Rare * 3 = Epic * 4 = Legendary */ /* WEAPONS * 0 = Axe * 1 = Mace * 2 = Sword */ /* STATS * 0 = MQ - Motivational Quotient - Charisma * 1 = PQ - Physical Quotient - Vitality * 2 = IQ - Intelligence Quotient - Intellect * 3 = EQ - Experience Quotient - Wisdom * 4 = LQ - Learning Agility Quotient - Dexterity * 5 = TQ - Technical Quotient - Tactics */ /** @dev used to manage payment in MANA */ contract MANAInterface { function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); } contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract ChainbreakersItemsERC721 is ERC721Token("Chainbreakers Items", "CBI"), BasicAccessControl, randomRange { address proxyRegistryAddress; using SafeMath for uint256; using strings for *; uint256 public totalItems; uint256 public totalItemClass; uint256 public totalTokens; uint8 public currentGen; string _baseURI = "http://api.chainbreakers.io/api/v1/items/metadata?tokenId="; uint public presaleStart = 1541073600; // use as seed for random address private lastMinter; ItemClass[] private globalClasses; mapping(uint256 => ItemData) public tokenToData; mapping(uint256 => ItemClass) public classIdToClass; struct ItemClass { uint256 classId; string name; uint16 amount; string hostfile; uint16 minLevel; uint16 rarity; uint16 weapon; uint[] category; uint[] statsMin; uint[] statsMax; string desc; uint256 total; uint price; bool active; } struct ItemData { uint256 tokenId; uint256 classId; uint[] stats; uint8 gen; } event ItemMinted(uint classId, uint price, uint256 total, uint tokenId); event GenerationIncreased(uint8 currentGen); event OwnerPayed(uint amount); event OwnerPayedETH(uint amount); // declare interface for communication between smart contracts MANAInterface MANAContract; /* HELPER FUNCTIONS - START */ /** @dev Concatenate two strings * @param _a The first string * @param _b The second string */ function addToString(string _a, string _b) internal pure returns(string) { return _a.toSlice().concat(_b.toSlice()); } /** @dev Converts an uint to a string * @notice used with addToString() to generate the tokenURI * @param i The uint you want to convert into a string */ function uint2str(uint i) internal pure returns(string) { if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } /* HELPER FUNCTIONS - END */ constructor(address _proxyRegistryAddress) public { proxyRegistryAddress = _proxyRegistryAddress; } /** @dev changes the date of the start of the presale * @param _start Timestamp the presale starts */ function changePresaleData(uint _start) public onlyModerators { presaleStart = _start; } /** @dev Used to init the communication between our contracts * @param _manaContractAddress The contract address for the currency you want to accept e.g. MANA */ function setDatabase(address _manaContractAddress) public onlyModerators { MANAContract = MANAInterface(_manaContractAddress); // change to official MANA contract address alter (0x0f5d2fb29fb7d3cfee444a200298f468908cc942) } /** @dev changes the tokenURI of all minted items + the _baseURI value * @param _newBaseURI base url to the api which reads the meta data from the contract e.g. "http://api.chainbreakers.io/api/v1/items/metadata?tokenId=" */ function changeBaseURIAll(string _newBaseURI) public onlyModerators { _baseURI = _newBaseURI; for(uint a = 0; a < totalTokens; a++) { uint tokenId = tokenByIndex(a); _setTokenURI(tokenId, addToString(_newBaseURI, uint2str(tokenId))); } } /** @dev changes the _baseURI value * @param _newBaseURI base url to the api which reads the meta data from the contract e.g. "http://api.chainbreakers.io/api/v1/items/metadata?tokenId=" */ function changeBaseURI(string _newBaseURI) public onlyModerators { _baseURI = _newBaseURI; } /** @dev changes the active state of an item class by its class id * @param _classId calss id of the item class * @param _active active state of the item class */ function editActiveFromClassId(uint256 _classId, bool _active) public onlyModerators { ItemClass storage _itemClass = classIdToClass[_classId]; _itemClass.active = _active; } /** @dev Adds an item to the contract which can be minted by the user paying the selected currency (MANA) * @notice You will find a list of the meanings of the individual indexes on top of the document * @param _name The name of the item * @param _rarity Defines the rarity on an item * @param _weapon Defines which weapon this item is * @param _statsMin An array of integers of the lowest stats an item can have * @param _statsMax An array of integers of the highest stats an item can have * @param _amount Defines how many items can be minted in general * @param _hostfile A string contains links to the 3D object, the icon and the thumbnail * @notice All links inside the _hostfile string has to be seperated by commas. Use `.split(",")` to get an array in frontend * @param _minLevel The lowest level a unit has to be to equip this item * @param _desc An optional item description used for legendary items mostly * @param _price The price of the item */ function addItemWithClassAndData(string _name, uint16 _rarity, uint16 _weapon, uint[] _statsMin, uint[] _statsMax, uint16 _amount, string _hostfile, uint16 _minLevel, string _desc, uint _price) public onlyModerators { ItemClass storage _itemClass = classIdToClass[totalItemClass]; _itemClass.classId = totalItemClass; _itemClass.name = _name; _itemClass.amount = _amount; _itemClass.rarity = _rarity; _itemClass.weapon = _weapon; _itemClass.statsMin = _statsMin; _itemClass.statsMax = _statsMax; _itemClass.hostfile = _hostfile; _itemClass.minLevel = _minLevel; _itemClass.desc = _desc; _itemClass.total = 0; _itemClass.price = _price; _itemClass.active = true; totalItemClass = globalClasses.push(_itemClass); totalItems++; } /** @dev The function the user calls to buy the selected item for a given price * @notice The price of the items increases after each bought item by a given amount * @param _classId The class id of the item which the user wants to buy */ function buyItem(uint256 _classId) public { require(now > presaleStart, "The presale is not started yet"); ItemClass storage class = classIdToClass[_classId]; require(class.active == true, "This item is not for sale"); require(class.amount > 0); require(class.total < class.amount, "Sold out"); require(class.statsMin.length == class.statsMax.length); if (class.price > 0) { require(MANAContract != address(0), "Invalid contract address for MANA. Please use the setDatabase() function first."); require(MANAContract.transferFrom(msg.sender, address(this), class.price) == true, "Failed transfering MANA"); } _mintItem(_classId, msg.sender); } /** @dev This function mints the item on the blockchain and generates an ERC721 token * @notice All stats of the item are randomly generated by using the getRandom() function using min and max values * @param _classId The class id of the item which one will be minted * @param _address The address of the owner of the new item */ function _mintItem(uint256 _classId, address _address) internal { ItemClass storage class = classIdToClass[_classId]; uint[] memory stats = new uint[](6); for(uint j = 0; j < class.statsMin.length; j++) { if (class.statsMax[j] > 0) { if (stats.length == class.statsMin.length) { stats[j] = getRandom(class.statsMin[j], class.statsMax[j], uint8(j + _classId + class.total), lastMinter); } } else { if (stats.length == class.statsMin.length) { stats[j] = 0; } } } ItemData storage _itemData = tokenToData[totalTokens + 1]; _itemData.tokenId = totalTokens + 1; _itemData.classId = _classId; _itemData.stats = stats; _itemData.gen = currentGen; class.total += 1; totalTokens += 1; _mint(_address, totalTokens); _setTokenURI(totalTokens, addToString(_baseURI, uint2str(totalTokens))); lastMinter = _address; emit ItemMinted(class.classId, class.price, class.total, totalTokens); } /** @dev Gets the min and the max range of stats a given class id can have * @param _classId The class id of the item you want to return the stats of * @return statsMin An array of the lowest stats the given item can have * @return statsMax An array of the highest stats the given item can have */ function getStatsRange(uint256 _classId) public view returns(uint[] statsMin, uint[] statsMax) { return (classIdToClass[_classId].statsMin, classIdToClass[_classId].statsMax); } /** @dev Gets information about the item stands behind the given token * @param _tokenId The id of the token you want to get the item data from * @return tokenId The id of the token * @return classId The class id of the item behind the token * @return stats The randomly generated stats of the item behind the token * @return gen The generation of the item */ function getItemDataByToken(uint256 _tokenId) public view returns(uint256 tokenId, uint256 classId, uint[] stats, uint8 gen) { return (tokenToData[_tokenId].tokenId, tokenToData[_tokenId].classId, tokenToData[_tokenId].stats, tokenToData[_tokenId].gen); } /** @dev Returns information about the item category of the given class id * @param _classId The class id of the item you want to return the stats of * @return classId The class id of the item * @return category An array contains information about the category of the item */ function getItemCategory(uint256 _classId) public view returns(uint256 classId, uint[] category) { return (classIdToClass[_classId].classId, classIdToClass[_classId].category); } /** @dev Edits the item class * @param _classId The class id of the item you want to edit * @param _name The name of the item * @param _rarity Defines the rarity on an item * @param _weapon Defines which weapon this item is * @param _statsMin An array of integers of the lowest stats an item can have * @param _statsMax An array of integers of the highest stats an item can have * @param _amount Defines how many items can be minted in general * @param _hostfile A string contains links to the 3D object, the icon and the thumbnail * @notice All links inside the _hostfile string has to be seperated by commas. Use `.split(",")` to get an array in frontend * @param _minLevel The lowest level a unit has to be to equip this item * @param _desc An optional item description used for legendary items mostly * @param _price The price of the item */ function editClass(uint256 _classId, string _name, uint16 _rarity, uint16 _weapon, uint[] _statsMin, uint[] _statsMax, uint16 _amount, string _hostfile, uint16 _minLevel, string _desc, uint _price) public onlyModerators { ItemClass storage _itemClass = classIdToClass[_classId]; _itemClass.name = _name; _itemClass.rarity = _rarity; _itemClass.weapon = _weapon; _itemClass.statsMin = _statsMin; _itemClass.statsMax = _statsMax; _itemClass.amount = _amount; _itemClass.hostfile = _hostfile; _itemClass.minLevel = _minLevel; _itemClass.desc = _desc; _itemClass.price = _price; } /** @dev Returns a count of created item classes * @return totalClasses Integer of how many items are able to be minted */ function countItemsByClass() public view returns(uint totalClasses) { return (globalClasses.length); } /** @dev This function mints an item as a quest reward. The quest contract needs to be added as a moderator * @param _classId The id of the item should be minted * @param _address The address of the future owner of the minted item */ function mintItemFromQuest(uint256 _classId, address _address) public onlyModerators { _mintItem(_classId, _address); } /** @dev Changes the tokenURI from a minted item by its tokenId * @param _tokenId The id of the token * @param _uri The new URI of the token for metadata e.g. http://api.chainbreakers.io/api/v1/items/metadata?tokenId=TOKEN_ID */ function changeURIFromTokenByTokenId(uint256 _tokenId, string _uri) public onlyModerators { _setTokenURI(_tokenId, _uri); } function increaseGen() public onlyModerators { currentGen += 1; emit GenerationIncreased(currentGen); } /** @dev Function to get a given amount of MANA from this contract. * @param _amount The amount of coins you want to get from this contract. */ function payOwner(uint _amount) public onlyOwner { MANAContract.transfer(msg.sender, _amount); emit OwnerPayed(_amount); } /** @dev Returns all MANA from this contract to the owner of the contract. */ function payOwnerAll() public onlyOwner { uint tokens = MANAContract.balanceOf(address(this)); MANAContract.transfer(msg.sender, tokens); emit OwnerPayed(tokens); } /** @dev Function to get a given amount of ETH from this contract. * @param _amount The amount of coins you want to get from this contract. */ function payOwnerETH(uint _amount) public onlyOwner { msg.sender.transfer(_amount); emit OwnerPayedETH(_amount); } /** @dev Returns all ETH from this contract to the owner of the contract. */ function payOwnerAllETH() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); emit OwnerPayedETH(balance); } function isApprovedForAll(address owner, address operator) public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (proxyRegistry.proxies(owner) == operator) { return true; } return super.isApprovedForAll(owner, operator); } }
* @dev used to manage payment in MANA */
contract MANAInterface { function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); }
1,760,263
[ 1, 3668, 358, 10680, 5184, 316, 20972, 37, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 20972, 37, 1358, 288, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 1769, 203, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 1769, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 1769, 203, 203, 203, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.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 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.4._ */ 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.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import { IUniswapV3MintCallback } from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol"; import { IUniswapV3SwapCallback } from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol"; import {GUniPoolStorage} from "./abstract/GUniPoolStorage.sol"; import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {TickMath} from "./vendor/uniswap/TickMath.sol"; import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { FullMath, LiquidityAmounts } from "./vendor/uniswap/LiquidityAmounts.sol"; contract GUniPool is IUniswapV3MintCallback, IUniswapV3SwapCallback, GUniPoolStorage { using SafeERC20 for IERC20; using TickMath for int24; event Minted( address receiver, uint256 mintAmount, uint256 amount0In, uint256 amount1In, uint128 liquidityMinted ); event Burned( address receiver, uint256 burnAmount, uint256 amount0Out, uint256 amount1Out, uint128 liquidityBurned ); event Rebalance( int24 lowerTick_, int24 upperTick_, uint128 liquidityBefore, uint128 liquidityAfter ); event FeesEarned(uint256 feesEarned0, uint256 feesEarned1); // solhint-disable-next-line max-line-length constructor(address payable _gelato) GUniPoolStorage(_gelato) {} // solhint-disable-line no-empty-blocks /// @notice Uniswap V3 callback fn, called back on pool.mint function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata /*_data*/ ) external override { require(msg.sender == address(pool), "callback caller"); if (amount0Owed > 0) token0.safeTransfer(msg.sender, amount0Owed); if (amount1Owed > 0) token1.safeTransfer(msg.sender, amount1Owed); } /// @notice Uniswap v3 callback fn, called back on pool.swap function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata /*data*/ ) external override { require(msg.sender == address(pool), "callback caller"); if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta)); else if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta)); } // User functions => Should be called via a Router /// @notice mint fungible G-UNI tokens, fractional shares of a Uniswap V3 position /// @dev to compute the amouint of tokens necessary to mint `mintAmount` see getMintAmounts /// @param mintAmount The number of G-UNI tokens to mint /// @param receiver The account to receive the minted tokens /// @return amount0 amount of token0 transferred from msg.sender to mint `mintAmount` /// @return amount1 amount of token1 transferred from msg.sender to mint `mintAmount` /// @return liquidityMinted amount of liquidity added to the underlying Uniswap V3 position // solhint-disable-next-line function-max-lines, code-complexity function mint(uint256 mintAmount, address receiver) external nonReentrant returns ( uint256 amount0, uint256 amount1, uint128 liquidityMinted ) { require(mintAmount > 0, "mint 0"); uint256 totalSupply = totalSupply(); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); if (totalSupply > 0) { (uint256 amount0Current, uint256 amount1Current) = getUnderlyingBalances(); amount0 = FullMath.mulDivRoundingUp( amount0Current, mintAmount, totalSupply ); amount1 = FullMath.mulDivRoundingUp( amount1Current, mintAmount, totalSupply ); } else { // if supply is 0 mintAmount == liquidity to deposit (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, lowerTick.getSqrtRatioAtTick(), upperTick.getSqrtRatioAtTick(), SafeCast.toUint128(mintAmount) ); } // transfer amounts owed to contract if (amount0 > 0) { token0.safeTransferFrom(msg.sender, address(this), amount0); } if (amount1 > 0) { token1.safeTransferFrom(msg.sender, address(this), amount1); } // deposit as much new liquidity as possible liquidityMinted = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, lowerTick.getSqrtRatioAtTick(), upperTick.getSqrtRatioAtTick(), amount0, amount1 ); pool.mint(address(this), lowerTick, upperTick, liquidityMinted, ""); _mint(receiver, mintAmount); emit Minted(receiver, mintAmount, amount0, amount1, liquidityMinted); } /// @notice burn G-UNI tokens (fractional shares of a Uniswap V3 position) and receive tokens /// @param burnAmount The number of G-UNI tokens to burn /// @param receiver The account to receive the underlying amounts of token0 and token1 /// @return amount0 amount of token0 transferred to receiver for burning `burnAmount` /// @return amount1 amount of token1 transferred to receiver for burning `burnAmount` /// @return liquidityBurned amount of liquidity removed from the underlying Uniswap V3 position // solhint-disable-next-line function-max-lines function burn(uint256 burnAmount, address receiver) external nonReentrant returns ( uint256 amount0, uint256 amount1, uint128 liquidityBurned ) { require(burnAmount > 0, "burn 0"); uint256 totalSupply = totalSupply(); (uint128 liquidity, , , , ) = pool.positions(_getPositionID()); _burn(msg.sender, burnAmount); uint256 liquidityBurned_ = FullMath.mulDiv(burnAmount, liquidity, totalSupply); liquidityBurned = SafeCast.toUint128(liquidityBurned_); (uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1) = _withdraw(lowerTick, upperTick, liquidityBurned); _applyFees(fee0, fee1); (fee0, fee1) = _subtractAdminFees(fee0, fee1); emit FeesEarned(fee0, fee1); amount0 = burn0 + FullMath.mulDiv( token0.balanceOf(address(this)) - burn0 - managerBalance0 - gelatoBalance0, burnAmount, totalSupply ); amount1 = burn1 + FullMath.mulDiv( token1.balanceOf(address(this)) - burn1 - managerBalance1 - gelatoBalance1, burnAmount, totalSupply ); if (amount0 > 0) { token0.safeTransfer(receiver, amount0); } if (amount1 > 0) { token1.safeTransfer(receiver, amount1); } emit Burned(receiver, burnAmount, amount0, amount1, liquidityBurned); } // Manager Functions => Called by Pool Manager /// @notice Change the range of underlying UniswapV3 position, only manager can call /// @dev When changing the range the inventory of token0 and token1 may be rebalanced /// with a swap to deposit as much liquidity as possible into the new position. Swap parameters /// can be computed by simulating the whole operation: remove all liquidity, deposit as much /// as possible into new position, then observe how much of token0 or token1 is leftover. /// Swap a proportion of this leftover to deposit more liquidity into the position, since /// any leftover will be unused and sit idle until the next rebalance. /// @param newLowerTick The new lower bound of the position's range /// @param newUpperTick The new upper bound of the position's range /// @param swapThresholdPrice slippage parameter on the swap as a max or min sqrtPriceX96 /// @param swapAmountBPS amount of token to swap as proportion of total. Pass 0 to ignore swap. /// @param zeroForOne Which token to input into the swap (true = token0, false = token1) function executiveRebalance( int24 newLowerTick, int24 newUpperTick, uint160 swapThresholdPrice, uint256 swapAmountBPS, bool zeroForOne ) external onlyManager { (uint128 liquidity, , , , ) = pool.positions(_getPositionID()); if (liquidity > 0) { (, , uint256 fee0, uint256 fee1) = _withdraw(lowerTick, upperTick, liquidity); _applyFees(fee0, fee1); (fee0, fee1) = _subtractAdminFees(fee0, fee1); emit FeesEarned(fee0, fee1); } lowerTick = newLowerTick; upperTick = newUpperTick; uint256 reinvest0 = token0.balanceOf(address(this)) - managerBalance0 - gelatoBalance0; uint256 reinvest1 = token1.balanceOf(address(this)) - managerBalance1 - gelatoBalance1; _deposit( newLowerTick, newUpperTick, reinvest0, reinvest1, swapThresholdPrice, swapAmountBPS, zeroForOne ); (uint128 newLiquidity, , , , ) = pool.positions(_getPositionID()); require(newLiquidity > 0, "new position 0"); emit Rebalance(newLowerTick, newUpperTick, liquidity, newLiquidity); } // Gelatofied functions => Automatically called by Gelato /// @notice Reinvest fees earned into underlying position, only gelato executors can call /// Position bounds CANNOT be altered by gelato, only manager may via executiveRebalance. /// Frequency of rebalance configured with gelatoRebalanceBPS, alterable by manager. function rebalance( uint160 swapThresholdPrice, uint256 swapAmountBPS, bool zeroForOne, uint256 feeAmount, address paymentToken ) external gelatofy(feeAmount, paymentToken) { if (swapAmountBPS > 0) { _checkSlippage(swapThresholdPrice, zeroForOne); } (uint128 liquidity, , , , ) = pool.positions(_getPositionID()); _rebalance( liquidity, swapThresholdPrice, swapAmountBPS, zeroForOne, feeAmount, paymentToken ); (uint128 newLiquidity, , , , ) = pool.positions(_getPositionID()); require(newLiquidity >= liquidity, "liquidity decrease"); emit Rebalance(lowerTick, upperTick, liquidity, newLiquidity); } /// @notice withdraw manager fees accrued, only gelato executors can call. /// Target account to receive fees is managerTreasury, alterable by manager. /// Frequency of withdrawals configured with gelatoWithdrawBPS, alterable by manager. function withdrawManagerBalance(uint256 feeAmount, address feeToken) external gelatofy(feeAmount, feeToken) { (uint256 amount0, uint256 amount1) = _balancesToWithdraw( managerBalance0, managerBalance1, feeAmount, feeToken ); managerBalance0 = 0; managerBalance1 = 0; if (amount0 > 0) { token0.safeTransfer(managerTreasury, amount0); } if (amount1 > 0) { token1.safeTransfer(managerTreasury, amount1); } } /// @notice withdraw gelato fees accrued, only gelato executors can call. /// Frequency of withdrawals configured with gelatoWithdrawBPS, alterable by manager. function withdrawGelatoBalance(uint256 feeAmount, address feeToken) external gelatofy(feeAmount, feeToken) { (uint256 amount0, uint256 amount1) = _balancesToWithdraw( gelatoBalance0, gelatoBalance1, feeAmount, feeToken ); gelatoBalance0 = 0; gelatoBalance1 = 0; if (amount0 > 0) { token0.safeTransfer(GELATO, amount0); } if (amount1 > 0) { token1.safeTransfer(GELATO, amount1); } } function _balancesToWithdraw( uint256 balance0, uint256 balance1, uint256 feeAmount, address feeToken ) internal view returns (uint256 amount0, uint256 amount1) { if (feeToken == address(token0)) { require( (balance0 * gelatoWithdrawBPS) / 10000 >= feeAmount, "high fee" ); amount0 = balance0 - feeAmount; amount1 = balance1; } else if (feeToken == address(token1)) { require( (balance1 * gelatoWithdrawBPS) / 10000 >= feeAmount, "high fee" ); amount1 = balance1 - feeAmount; amount0 = balance0; } else { revert("wrong token"); } } // View functions /// @notice compute maximum G-UNI tokens that can be minted from `amount0Max` and `amount1Max` /// @param amount0Max The maximum amount of token0 to forward on mint /// @param amount0Max The maximum amount of token1 to forward on mint /// @return amount0 actual amount of token0 to forward when minting `mintAmount` /// @return amount1 actual amount of token1 to forward when minting `mintAmount` /// @return mintAmount maximum number of G-UNI tokens to mint function getMintAmounts(uint256 amount0Max, uint256 amount1Max) external view returns ( uint256 amount0, uint256 amount1, uint256 mintAmount ) { uint256 totalSupply = totalSupply(); if (totalSupply > 0) { (amount0, amount1, mintAmount) = _computeMintAmounts( totalSupply, amount0Max, amount1Max ); } else { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); uint128 newLiquidity = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, lowerTick.getSqrtRatioAtTick(), upperTick.getSqrtRatioAtTick(), amount0Max, amount1Max ); mintAmount = uint256(newLiquidity); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, lowerTick.getSqrtRatioAtTick(), upperTick.getSqrtRatioAtTick(), newLiquidity ); } } /// @notice compute total underlying holdings of the G-UNI token supply /// includes current liquidity invested in uniswap position, current fees earned /// and any uninvested leftover (but does not include manager or gelato fees accrued) /// @return amount0Current current total underlying balance of token0 /// @return amount1Current current total underlying balance of token1 function getUnderlyingBalances() public view returns (uint256 amount0Current, uint256 amount1Current) { (uint160 sqrtRatioX96, int24 tick, , , , , ) = pool.slot0(); return _getUnderlyingBalances(sqrtRatioX96, tick); } function getUnderlyingBalancesAtPrice(uint160 sqrtRatioX96) external view returns (uint256 amount0Current, uint256 amount1Current) { (, int24 tick, , , , , ) = pool.slot0(); return _getUnderlyingBalances(sqrtRatioX96, tick); } // solhint-disable-next-line function-max-lines function _getUnderlyingBalances(uint160 sqrtRatioX96, int24 tick) internal view returns (uint256 amount0Current, uint256 amount1Current) { ( uint128 liquidity, uint256 feeGrowthInside0Last, uint256 feeGrowthInside1Last, uint128 tokensOwed0, uint128 tokensOwed1 ) = pool.positions(_getPositionID()); // compute current holdings from liquidity (amount0Current, amount1Current) = LiquidityAmounts .getAmountsForLiquidity( sqrtRatioX96, lowerTick.getSqrtRatioAtTick(), upperTick.getSqrtRatioAtTick(), liquidity ); // compute current fees earned uint256 fee0 = _computeFeesEarned(true, feeGrowthInside0Last, tick, liquidity) + uint256(tokensOwed0); uint256 fee1 = _computeFeesEarned(false, feeGrowthInside1Last, tick, liquidity) + uint256(tokensOwed1); (fee0, fee1) = _subtractAdminFees(fee0, fee1); // add any leftover in contract to current holdings amount0Current += fee0 + token0.balanceOf(address(this)) - managerBalance0 - gelatoBalance0; amount1Current += fee1 + token1.balanceOf(address(this)) - managerBalance1 - gelatoBalance1; } // Private functions // solhint-disable-next-line function-max-lines function _rebalance( uint128 liquidity, uint160 swapThresholdPrice, uint256 swapAmountBPS, bool zeroForOne, uint256 feeAmount, address paymentToken ) private { uint256 leftover0 = token0.balanceOf(address(this)) - managerBalance0 - gelatoBalance0; uint256 leftover1 = token1.balanceOf(address(this)) - managerBalance1 - gelatoBalance1; (, , uint256 feesEarned0, uint256 feesEarned1) = _withdraw(lowerTick, upperTick, liquidity); _applyFees(feesEarned0, feesEarned1); (feesEarned0, feesEarned1) = _subtractAdminFees( feesEarned0, feesEarned1 ); emit FeesEarned(feesEarned0, feesEarned1); feesEarned0 += leftover0; feesEarned1 += leftover1; if (paymentToken == address(token0)) { require( (feesEarned0 * gelatoRebalanceBPS) / 10000 >= feeAmount, "high fee" ); leftover0 = token0.balanceOf(address(this)) - managerBalance0 - gelatoBalance0 - feeAmount; leftover1 = token1.balanceOf(address(this)) - managerBalance1 - gelatoBalance1; } else if (paymentToken == address(token1)) { require( (feesEarned1 * gelatoRebalanceBPS) / 10000 >= feeAmount, "high fee" ); leftover0 = token0.balanceOf(address(this)) - managerBalance0 - gelatoBalance0; leftover1 = token1.balanceOf(address(this)) - managerBalance1 - gelatoBalance1 - feeAmount; } else { revert("wrong token"); } _deposit( lowerTick, upperTick, leftover0, leftover1, swapThresholdPrice, swapAmountBPS, zeroForOne ); } // solhint-disable-next-line function-max-lines function _withdraw( int24 lowerTick_, int24 upperTick_, uint128 liquidity ) private returns ( uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1 ) { uint256 preBalance0 = token0.balanceOf(address(this)); uint256 preBalance1 = token1.balanceOf(address(this)); (burn0, burn1) = pool.burn(lowerTick_, upperTick_, liquidity); pool.collect( address(this), lowerTick_, upperTick_, type(uint128).max, type(uint128).max ); fee0 = token0.balanceOf(address(this)) - preBalance0 - burn0; fee1 = token1.balanceOf(address(this)) - preBalance1 - burn1; } // solhint-disable-next-line function-max-lines function _deposit( int24 lowerTick_, int24 upperTick_, uint256 amount0, uint256 amount1, uint160 swapThresholdPrice, uint256 swapAmountBPS, bool zeroForOne ) private { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); // First, deposit as much as we can uint128 baseLiquidity = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, lowerTick_.getSqrtRatioAtTick(), upperTick_.getSqrtRatioAtTick(), amount0, amount1 ); if (baseLiquidity > 0) { (uint256 amountDeposited0, uint256 amountDeposited1) = pool.mint( address(this), lowerTick_, upperTick_, baseLiquidity, "" ); amount0 -= amountDeposited0; amount1 -= amountDeposited1; } int256 swapAmount = SafeCast.toInt256( ((zeroForOne ? amount0 : amount1) * swapAmountBPS) / 10000 ); if (swapAmount > 0) { _swapAndDeposit( lowerTick_, upperTick_, amount0, amount1, swapAmount, swapThresholdPrice, zeroForOne ); } } function _swapAndDeposit( int24 lowerTick_, int24 upperTick_, uint256 amount0, uint256 amount1, int256 swapAmount, uint160 swapThresholdPrice, bool zeroForOne ) private returns (uint256 finalAmount0, uint256 finalAmount1) { (int256 amount0Delta, int256 amount1Delta) = pool.swap( address(this), zeroForOne, swapAmount, swapThresholdPrice, "" ); finalAmount0 = uint256(SafeCast.toInt256(amount0) - amount0Delta); finalAmount1 = uint256(SafeCast.toInt256(amount1) - amount1Delta); // Add liquidity a second time (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); uint128 liquidityAfterSwap = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, lowerTick_.getSqrtRatioAtTick(), upperTick_.getSqrtRatioAtTick(), finalAmount0, finalAmount1 ); if (liquidityAfterSwap > 0) { pool.mint( address(this), lowerTick_, upperTick_, liquidityAfterSwap, "" ); } } // solhint-disable-next-line function-max-lines, code-complexity function _computeMintAmounts( uint256 totalSupply, uint256 amount0Max, uint256 amount1Max ) private view returns ( uint256 amount0, uint256 amount1, uint256 mintAmount ) { (uint256 amount0Current, uint256 amount1Current) = getUnderlyingBalances(); // compute proportional amount of tokens to mint if (amount0Current == 0 && amount1Current > 0) { mintAmount = FullMath.mulDiv( amount1Max, totalSupply, amount1Current ); } else if (amount1Current == 0 && amount0Current > 0) { mintAmount = FullMath.mulDiv( amount0Max, totalSupply, amount0Current ); } else if (amount0Current == 0 && amount1Current == 0) { revert(""); } else { // only if both are non-zero uint256 amount0Mint = FullMath.mulDiv(amount0Max, totalSupply, amount0Current); uint256 amount1Mint = FullMath.mulDiv(amount1Max, totalSupply, amount1Current); require(amount0Mint > 0 && amount1Mint > 0, "mint 0"); mintAmount = amount0Mint < amount1Mint ? amount0Mint : amount1Mint; } // compute amounts owed to contract amount0 = FullMath.mulDivRoundingUp( mintAmount, amount0Current, totalSupply ); amount1 = FullMath.mulDivRoundingUp( mintAmount, amount1Current, totalSupply ); } // solhint-disable-next-line function-max-lines function _computeFeesEarned( bool isZero, uint256 feeGrowthInsideLast, int24 tick, uint128 liquidity ) private view returns (uint256 fee) { uint256 feeGrowthOutsideLower; uint256 feeGrowthOutsideUpper; uint256 feeGrowthGlobal; if (isZero) { feeGrowthGlobal = pool.feeGrowthGlobal0X128(); (, , feeGrowthOutsideLower, , , , , ) = pool.ticks(lowerTick); (, , feeGrowthOutsideUpper, , , , , ) = pool.ticks(upperTick); } else { feeGrowthGlobal = pool.feeGrowthGlobal1X128(); (, , , feeGrowthOutsideLower, , , , ) = pool.ticks(lowerTick); (, , , feeGrowthOutsideUpper, , , , ) = pool.ticks(upperTick); } unchecked { // calculate fee growth below uint256 feeGrowthBelow; if (tick >= lowerTick) { feeGrowthBelow = feeGrowthOutsideLower; } else { feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower; } // calculate fee growth above uint256 feeGrowthAbove; if (tick < upperTick) { feeGrowthAbove = feeGrowthOutsideUpper; } else { feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper; } uint256 feeGrowthInside = feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove; fee = FullMath.mulDiv( liquidity, feeGrowthInside - feeGrowthInsideLast, 0x100000000000000000000000000000000 ); } } function _applyFees(uint256 _fee0, uint256 _fee1) private { gelatoBalance0 += (_fee0 * gelatoFeeBPS) / 10000; gelatoBalance1 += (_fee1 * gelatoFeeBPS) / 10000; managerBalance0 += (_fee0 * managerFeeBPS) / 10000; managerBalance1 += (_fee1 * managerFeeBPS) / 10000; } function _subtractAdminFees(uint256 rawFee0, uint256 rawFee1) private view returns (uint256 fee0, uint256 fee1) { uint256 deduct0 = (rawFee0 * (gelatoFeeBPS + managerFeeBPS)) / 10000; uint256 deduct1 = (rawFee1 * (gelatoFeeBPS + managerFeeBPS)) / 10000; fee0 = rawFee0 - deduct0; fee1 = rawFee1 - deduct1; } function _checkSlippage(uint160 swapThresholdPrice, bool zeroForOne) private view { uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = gelatoSlippageInterval; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); require(tickCumulatives.length == 2, "array len"); uint160 avgSqrtRatioX96; unchecked { int24 avgTick = int24( (tickCumulatives[1] - tickCumulatives[0]) / int56(uint56(gelatoSlippageInterval)) ); avgSqrtRatioX96 = avgTick.getSqrtRatioAtTick(); } uint160 maxSlippage = (avgSqrtRatioX96 * gelatoSlippageBPS) / 10000; if (zeroForOne) { require( swapThresholdPrice >= avgSqrtRatioX96 - maxSlippage, "high slippage" ); } else { require( swapThresholdPrice <= avgSqrtRatioX96 + maxSlippage, "high slippage" ); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import {Gelatofied} from "./Gelatofied.sol"; import {OwnableUninitialized} from "./OwnableUninitialized.sol"; import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; /// @dev Single Global upgradeable state var storage base: APPEND ONLY /// @dev Add all inherited contracts with state vars here: APPEND ONLY /// @dev ERC20Upgradable Includes Initialize // solhint-disable-next-line max-states-count abstract contract GUniPoolStorage is ERC20Upgradeable, /* XXXX DONT MODIFY ORDERING XXXX */ ReentrancyGuardUpgradeable, OwnableUninitialized, Gelatofied // APPEND ADDITIONAL BASE WITH STATE VARS BELOW: // XXXX DONT MODIFY ORDERING XXXX { // solhint-disable-next-line const-name-snakecase string public constant version = "1.0.0"; // solhint-disable-next-line const-name-snakecase uint16 public constant gelatoFeeBPS = 100; // XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX int24 public lowerTick; int24 public upperTick; uint16 public gelatoRebalanceBPS; uint16 public gelatoWithdrawBPS; uint16 public gelatoSlippageBPS; uint32 public gelatoSlippageInterval; uint16 public managerFeeBPS; address public managerTreasury; uint256 public managerBalance0; uint256 public managerBalance1; uint256 public gelatoBalance0; uint256 public gelatoBalance1; IUniswapV3Pool public pool; IERC20 public token0; IERC20 public token1; // APPPEND ADDITIONAL STATE VARS BELOW: // XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX event UpdateAdminTreasury( address oldAdminTreasury, address newAdminTreasury ); event UpdateGelatoParams( uint16 gelatoRebalanceBPS, uint16 gelatoWithdrawBPS, uint16 gelatoSlippageBPS, uint32 gelatoSlippageInterval ); event SetManagerFee(uint16 managerFee); // solhint-disable-next-line max-line-length constructor(address payable _gelato) Gelatofied(_gelato) {} // solhint-disable-line no-empty-blocks /// @notice initialize storage variables on a new G-UNI pool, only called once /// @param _name name of G-UNI token /// @param _symbol symbol of G-UNI token /// @param _pool address of Uniswap V3 pool /// @param _managerFeeBPS proportion of fees earned that go to manager treasury /// note that the 4 above params are NOT UPDATEABLE AFTER INILIALIZATION /// @param _lowerTick initial lowerTick (only changeable with executiveRebalance) /// @param _lowerTick initial upperTick (only changeable with executiveRebalance) /// @param _manager_ address of manager (ownership can be transferred) function initialize( string memory _name, string memory _symbol, address _pool, uint16 _managerFeeBPS, int24 _lowerTick, int24 _upperTick, address _manager_ ) external initializer { require(_managerFeeBPS <= 10000 - gelatoFeeBPS, "mBPS"); // these variables are immutable after initialization pool = IUniswapV3Pool(_pool); token0 = IERC20(pool.token0()); token1 = IERC20(pool.token1()); managerFeeBPS = _managerFeeBPS; // if set to 0 here manager can still initialize later // these variables can be udpated by the manager gelatoSlippageInterval = 5 minutes; // default: last five minutes; gelatoSlippageBPS = 500; // default: 5% slippage gelatoWithdrawBPS = 100; // default: only auto withdraw if tx fee is lt 1% withdrawn gelatoRebalanceBPS = 200; // default: only rebalance if tx fee is lt 2% reinvested managerTreasury = _manager_; // default: treasury is admin lowerTick = _lowerTick; upperTick = _upperTick; _manager = _manager_; // e.g. "Gelato Uniswap V3 USDC/DAI LP" and "G-UNI" __ERC20_init(_name, _symbol); __ReentrancyGuard_init(); } /// @notice change configurable parameters, only manager can call /// @param newRebalanceBPS controls frequency of gelato rebalances: gas fee to execute /// rebalance can be gelatoRebalanceBPS proportion of fees earned since last rebalance /// @param newWithdrawBPS controls frequency of gelato withdrawals: gas fee to execute /// withdrawal can be gelatoWithdrawBPS proportion of fees accrued since last withdraw /// @param newSlippageBPS maximum slippage on swaps during gelato rebalance /// @param newSlippageInterval length of time for TWAP used in computing slippage on swaps /// @param newTreasury address where managerFee withdrawals are sent // solhint-disable-next-line code-complexity function updateGelatoParams( uint16 newRebalanceBPS, uint16 newWithdrawBPS, uint16 newSlippageBPS, uint32 newSlippageInterval, address newTreasury ) external onlyManager { require(newWithdrawBPS <= 10000, "BPS"); require(newRebalanceBPS <= 10000, "BPS"); require(newSlippageBPS <= 10000, "BPS"); emit UpdateGelatoParams( newRebalanceBPS, newWithdrawBPS, newSlippageBPS, newSlippageInterval ); if (newRebalanceBPS != 0) gelatoRebalanceBPS = newRebalanceBPS; if (newWithdrawBPS != 0) gelatoWithdrawBPS = newWithdrawBPS; if (newSlippageBPS != 0) gelatoSlippageBPS = newSlippageBPS; if (newSlippageInterval != 0) gelatoSlippageInterval = newSlippageInterval; if (newTreasury != address(0)) managerTreasury = newTreasury; } /// @notice initializeManagerFee sets a managerFee, only manager can call. /// If a manager fee was not set in the initialize function it can be set here /// but ONLY ONCE- after it is set to a non-zero value, managerFee can never be set again. /// @param _managerFeeBPS proportion of fees earned that are credited to manager in Basis Points function initializeManagerFee(uint16 _managerFeeBPS) external onlyManager { require(managerFeeBPS == 0, "fee"); require( _managerFeeBPS > 0 && _managerFeeBPS <= 10000 - gelatoFeeBPS, "mBPS" ); emit SetManagerFee(_managerFeeBPS); managerFeeBPS = _managerFeeBPS; } function renounceOwnership() public virtual override onlyManager { managerTreasury = address(0); managerFeeBPS = 0; managerBalance0 = 0; managerBalance1 = 0; super.renounceOwnership(); } function getPositionID() external view returns (bytes32 positionID) { return _getPositionID(); } function _getPositionID() internal view returns (bytes32 positionID) { return keccak256(abi.encodePacked(address(this), lowerTick, upperTick)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage /// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage abstract contract Gelatofied { using Address for address payable; using SafeERC20 for IERC20; // solhint-disable-next-line var-name-mixedcase address payable public immutable GELATO; address private constant _ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor(address payable _gelato) { GELATO = _gelato; } modifier gelatofy(uint256 _amount, address _paymentToken) { require(msg.sender == GELATO, "Gelatofied: Only gelato"); _; if (_paymentToken == _ETH) GELATO.sendValue(_amount); else IERC20(_paymentToken).safeTransfer(GELATO, _amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an manager) that can be granted exclusive access to * specific functions. * * By default, the manager account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyManager`, which can be applied to your functions to restrict their use to * the manager. */ /// @dev DO NOT ADD STATE VARIABLES - APPEND THEM TO GelatoUniV3PoolStorage /// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS - APPEND THEM TO GelatoUniV3PoolStorage abstract contract OwnableUninitialized { address internal _manager; event OwnershipTransferred( address indexed previousManager, address indexed newManager ); /// @dev Initializes the contract setting the deployer as the initial manager. /// CONSTRUCTOR EMPTY - USE INITIALIZIABLE INSTEAD // solhint-disable-next-line no-empty-blocks constructor() {} /** * @dev Returns the address of the current manager. */ function manager() public view virtual returns (address) { return _manager; } /** * @dev Throws if called by any account other than the manager. */ modifier onlyManager() { require(manager() == msg.sender, "Ownable: caller is not the manager"); _; } /** * @dev Leaves the contract without manager. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current manager. * * NOTE: Renouncing ownership will leave the contract without an manager, * thereby removing any functionality that is only available to the manager. */ function renounceOwnership() public virtual onlyManager { emit OwnershipTransferred(_manager, address(0)); _manager = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current manager. */ function transferOwnership(address newOwner) public virtual onlyManager { require( newOwner != address(0), "Ownable: new manager is the zero address" ); emit OwnershipTransferred(_manager, newOwner); _manager = newOwner; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. // EDIT for 0.8 compatibility: // see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256 uint256 twos = denominator & (~denominator + 1); // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import {FullMath} from "./FullMath.sol"; import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128( FullMath.mulDiv( amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96 ) ); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128( FullMath.mulDiv( amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96 ) ); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0( sqrtRatioAX96, sqrtRatioBX96, amount0 ); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1( sqrtRatioAX96, sqrtRatioBX96, amount1 ); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The liquidity being valued /// @return amount0 The amount0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The liquidity being valued /// @return amount1 The amount1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96 ); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity( sqrtRatioAX96, sqrtRatioBX96, liquidity ); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity( sqrtRatioX96, sqrtRatioBX96, liquidity ); amount1 = getAmount1ForLiquidity( sqrtRatioAX96, sqrtRatioX96, liquidity ); } else { amount1 = getAmount1ForLiquidity( sqrtRatioAX96, sqrtRatioBX96, liquidity ); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); // EDIT: 0.8 compatibility require(absTick <= uint256(int256(MAX_TICK)), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160( (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1) ); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require( sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R" ); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24( (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128 ); int24 tickHi = int24( (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128 ); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } }
solhint-disable-next-line function-max-lines
function _withdraw( int24 lowerTick_, int24 upperTick_, uint128 liquidity ) private returns ( uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1 ) { uint256 preBalance0 = token0.balanceOf(address(this)); uint256 preBalance1 = token1.balanceOf(address(this)); (burn0, burn1) = pool.burn(lowerTick_, upperTick_, liquidity); pool.collect( address(this), lowerTick_, upperTick_, type(uint128).max, type(uint128).max ); fee0 = token0.balanceOf(address(this)) - preBalance0 - burn0; fee1 = token1.balanceOf(address(this)) - preBalance1 - burn1; }
454,049
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 445, 17, 1896, 17, 3548, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1918, 9446, 12, 203, 3639, 509, 3247, 2612, 6264, 67, 16, 203, 3639, 509, 3247, 3854, 6264, 67, 16, 203, 3639, 2254, 10392, 4501, 372, 24237, 203, 565, 262, 203, 3639, 3238, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 18305, 20, 16, 203, 5411, 2254, 5034, 18305, 21, 16, 203, 5411, 2254, 5034, 14036, 20, 16, 203, 5411, 2254, 5034, 14036, 21, 203, 3639, 262, 203, 565, 288, 203, 3639, 2254, 5034, 675, 13937, 20, 273, 1147, 20, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 675, 13937, 21, 273, 1147, 21, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 261, 70, 321, 20, 16, 18305, 21, 13, 273, 2845, 18, 70, 321, 12, 8167, 6264, 67, 16, 3854, 6264, 67, 16, 4501, 372, 24237, 1769, 203, 203, 3639, 2845, 18, 14676, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 2612, 6264, 67, 16, 203, 5411, 3854, 6264, 67, 16, 203, 5411, 618, 12, 11890, 10392, 2934, 1896, 16, 203, 5411, 618, 12, 11890, 10392, 2934, 1896, 203, 3639, 11272, 203, 203, 3639, 14036, 20, 273, 1147, 20, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 300, 675, 13937, 20, 300, 18305, 20, 31, 203, 3639, 14036, 21, 273, 1147, 21, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 300, 675, 13937, 21, 300, 18305, 21, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xE9a1a29462c9C64fC5Ffc2a449C09f90ABfb6B4D/sources/contracts/smart-wallet/TWAccountFactory.sol
@notice Returns the implementation of the Account.
function accountImplementation() external view override returns (address) { return address(_accountImplementation); }
7,037,374
[ 1, 1356, 326, 4471, 434, 326, 6590, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2236, 13621, 1435, 3903, 1476, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1758, 24899, 4631, 13621, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x0AbcaDdc3F22131b467F3f4E5cef6007e4a53268/sources/contracts/NFT.sol
* @dev Transfers the token via ERC721's _transfer() function if the collection is transferrable @param from Inherited from ERC721's _transfer() function @param to Inherited from ERC721's _transfer() function @param tokenId Inherited from ERC721's _transfer() function/
function _transfer( address from, address to, uint256 tokenId ) internal virtual override { require(transferable, "token is not transferable"); super._transfer(from, to, tokenId); }
16,360,387
[ 1, 1429, 18881, 326, 1147, 3970, 4232, 39, 27, 5340, 1807, 389, 13866, 1435, 445, 309, 326, 1849, 353, 7412, 354, 7119, 225, 628, 25953, 329, 628, 4232, 39, 27, 5340, 1807, 389, 13866, 1435, 445, 225, 358, 25953, 329, 628, 4232, 39, 27, 5340, 1807, 389, 13866, 1435, 445, 225, 1147, 548, 25953, 329, 628, 4232, 39, 27, 5340, 1807, 389, 13866, 1435, 445, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 5024, 3849, 288, 7010, 3639, 2583, 12, 13866, 429, 16, 315, 2316, 353, 486, 7412, 429, 8863, 203, 3639, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-04 */ /** *Submitted for verification at polygonscan.com on 2021-12-03 */ // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: contracts/interfaces/IUniswapV2Router.sol interface IUniswapV2Router { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity ^0.8.0; /** * @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); } // File: contracts/interfaces/IERC20Token.sol abstract contract IERC20Token is IERC20 { function upgrade(uint256 value) public virtual; } // File: contracts/Ownable.sol contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender || _owner == address(0x0), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/FundsRecovery.sol contract FundsRecovery is Ownable, ReentrancyGuard { address payable internal fundsDestination; IERC20Token public token; event DestinationChanged(address indexed previousDestination, address indexed newDestination); /** * Setting new destination of funds recovery. */ function setFundsDestination(address payable _newDestination) public virtual onlyOwner { require(_newDestination != address(0)); emit DestinationChanged(fundsDestination, _newDestination); fundsDestination = _newDestination; } /** * Getting funds destination address. */ function getFundsDestination() public view returns (address) { return fundsDestination; } /** * Possibility to recover funds in case they were sent to this address before smart contract deployment */ function claimEthers() public nonReentrant { require(fundsDestination != address(0)); fundsDestination.transfer(address(this).balance); } /** Transfers selected tokens into owner address. */ function claimTokens(address _token) public nonReentrant { require(fundsDestination != address(0)); require(_token != address(token), "native token funds can't be recovered"); uint256 _amount = IERC20Token(_token).balanceOf(address(this)); IERC20Token(_token).transfer(fundsDestination, _amount); } } // File: contracts/Utils.sol contract Utils { function getChainID() internal view returns (uint256) { uint256 chainID; assembly { chainID := chainid() } return chainID; } function max(uint a, uint b) internal pure returns (uint) { return a > b ? a : b; } function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } function round(uint a, uint m) internal pure returns (uint ) { return ((a + m - 1) / m) * m; } } // File: contracts/HermesImplementation.sol interface IdentityRegistry { function isRegistered(address _identity) external view returns (bool); function minimalHermesStake() external view returns (uint256); function getChannelAddress(address _identity, address _hermesId) external view returns (address); function getBeneficiary(address _identity) external view returns (address); function setBeneficiary(address _identity, address _newBeneficiary, bytes memory _signature) external; } // Hermes (channel balance provided by Herms, no staking/loans) contract HermesImplementation is FundsRecovery, Utils { using ECDSA for bytes32; string constant STAKE_RETURN_PREFIX = "Stake return request"; uint256 constant DELAY_SECONDS = 259200; // 3 days uint256 constant UNIT_SECONDS = 3600; // 1 unit = 1 hour = 3600 seconds uint16 constant PUNISHMENT_PERCENT = 4; // 0.04% IdentityRegistry internal registry; address internal operator; // TODO have master operator who could change operator or manage funds uint256 internal totalStake; // total amount staked by providers uint256 internal minStake; // minimal possible provider's stake (channel opening during promise settlement will use it) uint256 internal maxStake; // maximal allowed provider's stake uint256 internal hermesStake; // hermes stake is used to prove hermes' sustainability uint256 internal closingTimelock; // blocknumber after which getting stake back will become possible IUniswapV2Router internal dex; // any uniswap v2 compatible dex router address enum Status { Active, Paused, Punishment, Closed } // hermes states Status internal status; struct HermesFee { uint16 value; // subprocent amount. e.g. 2.5% = 250 uint64 validFrom; // timestamp from which fee is valid } HermesFee public lastFee; // default fee to look for HermesFee public previousFee; // previous fee is used if last fee is still not active // Our channel don't have balance, because we're always rebalancing into stake amount. struct Channel { uint256 settled; // total amount already settled by provider uint256 stake; // amount staked by identity to guarante channel size, it also serves as channel balance uint256 lastUsedNonce; // last known nonce, is used to protect signature based calls from replay attack uint256 timelock; // blocknumber after which channel balance can be decreased } mapping(bytes32 => Channel) public channels; struct Punishment { uint256 activationBlockTime; // block timestamp in which punishment was activated uint256 amount; // total amount of tokens locked because of punishment } Punishment public punishment; function getOperator() public view returns (address) { return operator; } function getChannelId(address _identity) public view returns (bytes32) { return keccak256(abi.encodePacked(_identity, address(this))); } function getChannelId(address _identity, string memory _type) public view returns (bytes32) { return keccak256(abi.encodePacked(_identity, address(this), _type)); } function getRegistry() public view returns (address) { return address(registry); } function getActiveFee() public view returns (uint256) { HermesFee memory _activeFee = (block.timestamp >= lastFee.validFrom) ? lastFee : previousFee; return uint256(_activeFee.value); } function getHermesStake() public view returns (uint256) { return hermesStake; } function getStakeThresholds() public view returns (uint256, uint256) { return (minStake, maxStake); } // Returns hermes state // Active - all operations are allowed. // Paused - no new channel openings. // Punishment - don't allow to open new channels, rebalance and withdraw funds. // Closed - no new channels, no rebalance, no stake increase. function getStatus() public view returns (Status) { return status; } event PromiseSettled(address indexed identity, bytes32 indexed channelId, address indexed beneficiary, uint256 amountSentToBeneficiary, uint256 fees, bytes32 lock); event NewStake(bytes32 indexed channelId, uint256 stakeAmount); event MinStakeValueUpdated(uint256 newMinStake); event MaxStakeValueUpdated(uint256 newMaxStake); event HermesFeeUpdated(uint16 newFee, uint64 validFrom); event HermesClosed(uint256 blockTimestamp); event ChannelOpeningPaused(); event ChannelOpeningActivated(); event FundsWithdrawned(uint256 amount, address beneficiary); event HermesStakeIncreased(uint256 newStake); event HermesPunishmentActivated(uint256 activationBlockTime); event HermesPunishmentDeactivated(); modifier onlyOperator() { require(msg.sender == operator, "Hermes: only hermes operator can call this function"); _; } /* ------------------------------------------- SETUP ------------------------------------------- */ // Because of proxy pattern this function is used insted of constructor. // Have to be called right after proxy deployment. function initialize(address _token, address _operator, uint16 _fee, uint256 _minStake, uint256 _maxStake, address payable _dexAddress) public virtual { require(!isInitialized(), "Hermes: have to be not initialized"); require(_token != address(0), "Hermes: token can't be deployd into zero address"); require(_operator != address(0), "Hermes: operator have to be set"); require(_fee <= 5000, "Hermes: fee can't be bigger than 50%"); require(_maxStake > _minStake, "Hermes: maxStake have to be bigger than minStake"); registry = IdentityRegistry(msg.sender); token = IERC20Token(_token); operator = _operator; lastFee = HermesFee(_fee, uint64(block.timestamp)); minStake = _minStake; maxStake = _maxStake; hermesStake = token.balanceOf(address(this)); // Approving all myst for dex, because MYST token's `transferFrom` is cheaper when there is approval of uint(-1) token.approve(_dexAddress, type(uint256).max); dex = IUniswapV2Router(_dexAddress); } function isInitialized() public view returns (bool) { return operator != address(0); } /* -------------------------------------- MAIN FUNCTIONALITY ----------------------------------- */ // Open incoming payments (also known as provider) channel. Can be called only by Registry. function openChannel(address _identity, uint256 _amountToStake) public { require(msg.sender == address(registry), "Hermes: only registry can open channels"); require(getStatus() == Status.Active, "Hermes: have to be in active state"); require(_amountToStake >= minStake, "Hermes: min stake amount not reached"); _increaseStake(getChannelId(_identity), _amountToStake, false); } // Settle promise // _preimage is random number generated by receiver used in HTLC function _settlePromise( bytes32 _channelId, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature, bool _takeFee, bool _ignoreStake ) private returns (uint256, uint256) { require( isHermesActive(), "Hermes: hermes have to be in active state" ); // if hermes is not active, then users can only take stake back require( validatePromise(_channelId, _amount, _transactorFee, _preimage, _signature), "Hermes: have to be properly signed payment promise" ); Channel storage _channel = channels[_channelId]; require(_channel.settled > 0 || _channel.stake >= minStake || _ignoreStake, "Hermes: not enough stake"); // If there are not enought funds to rebalance we have to enable punishment mode. uint256 _availableBalance = availableBalance(); if (_availableBalance < _channel.stake) { status = Status.Punishment; punishment.activationBlockTime = block.timestamp; emit HermesPunishmentActivated(block.timestamp); } // Calculate amount of tokens to be claimed. uint256 _unpaidAmount = _amount - _channel.settled; require(_unpaidAmount > _transactorFee, "Hermes: amount to settle should cover transactor fee"); // It is not allowed to settle more than maxStake / _channel.stake and than available balance. uint256 _maxSettlementAmount = max(maxStake, _channel.stake); if (_unpaidAmount > _availableBalance || _unpaidAmount > _maxSettlementAmount) { _unpaidAmount = min(_availableBalance, _maxSettlementAmount); } _channel.settled = _channel.settled + _unpaidAmount; // Increase already paid amount. uint256 _fees = _transactorFee + (_takeFee ? calculateHermesFee(_unpaidAmount) : 0); // Pay transactor fee if (_transactorFee > 0) { token.transfer(msg.sender, _transactorFee); } uint256 _amountToTransfer = _unpaidAmount -_fees; return (_amountToTransfer, _fees); } function settlePromise(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public { address _beneficiary = registry.getBeneficiary(_identity); require(_beneficiary != address(0), "Hermes: identity have to be registered, beneficiary have to be set"); // Settle promise and transfer calculated amount into beneficiary wallet bytes32 _channelId = getChannelId(_identity); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, true, false); token.transfer(_beneficiary, _amountToTransfer); emit PromiseSettled(_identity, _channelId, _beneficiary, _amountToTransfer, _fees, _preimage); } function payAndSettle(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature, address _beneficiary, bytes memory _beneficiarySignature) public { bytes32 _channelId = getChannelId(_identity, "withdrawal"); // Validate beneficiary to be signed by identity and be attached to given promise address _signer = keccak256(abi.encodePacked(getChainID(), _channelId, _amount, _preimage, _beneficiary)).recover(_beneficiarySignature); require(_signer == _identity, "Hermes: payAndSettle request should be properly signed"); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, false, true); token.transfer(_beneficiary, _amountToTransfer); emit PromiseSettled(_identity, _channelId, _beneficiary, _amountToTransfer, _fees, _preimage); } function settleWithBeneficiary(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _promiseSignature, address _newBeneficiary, bytes memory _beneficiarySignature) public { // Update beneficiary address registry.setBeneficiary(_identity, _newBeneficiary, _beneficiarySignature); // Settle promise and transfer calculated amount into beneficiary wallet bytes32 _channelId = getChannelId(_identity); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _promiseSignature, true, false); token.transfer(_newBeneficiary, _amountToTransfer); emit PromiseSettled(_identity, _channelId, _newBeneficiary, _amountToTransfer, _fees, _preimage); } function settleWithDEX(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public { address _beneficiary = registry.getBeneficiary(_identity); require(_beneficiary != address(0), "Hermes: identity have to be registered, beneficiary have to be set"); // Calculate amount to transfer and settle promise bytes32 _channelId = getChannelId(_identity); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, true, false); // Transfer funds into beneficiary wallet via DEX uint amountOutMin = 0; address[] memory path = new address[](2); path[0] = address(token); path[1] = dex.WETH(); dex.swapExactTokensForETH(_amountToTransfer, amountOutMin, path, _beneficiary, block.timestamp); emit PromiseSettled(_identity, _channelId, _beneficiary, _amountToTransfer, _fees, _preimage); } /* -------------------------------------- STAKE MANAGEMENT -------------------------------------- */ function _increaseStake(bytes32 _channelId, uint256 _amountToAdd, bool _duringSettlement) internal { Channel storage _channel = channels[_channelId]; uint256 _newStakeAmount = _channel.stake +_amountToAdd; require(_newStakeAmount <= maxStake, "Hermes: total amount to stake can't be bigger than maximally allowed"); require(_newStakeAmount >= minStake, "Hermes: stake can't be less than required min stake"); // We don't transfer tokens during settlements, they already locked in hermes contract. if (!_duringSettlement) { require(token.transferFrom(msg.sender, address(this), _amountToAdd), "Hermes: token transfer should succeed"); } _channel.stake = _newStakeAmount; totalStake = totalStake + _amountToAdd; emit NewStake(_channelId, _newStakeAmount); } // Anyone can increase channel's capacity by staking more into hermes function increaseStake(bytes32 _channelId, uint256 _amount) public { require(getStatus() != Status.Closed, "hermes should be not closed"); _increaseStake(_channelId, _amount, false); } // Settlement which will increase channel stake instead of transfering funds into beneficiary wallet. function settleIntoStake(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public { bytes32 _channelId = getChannelId(_identity); (uint256 _stakeIncreaseAmount, uint256 _paidFees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, true, true); emit PromiseSettled(_identity, _channelId, address(this), _stakeIncreaseAmount, _paidFees, _preimage); _increaseStake(_channelId, _stakeIncreaseAmount, true); } // Withdraw part of stake. This will also decrease channel balance. function decreaseStake(address _identity, uint256 _amount, uint256 _transactorFee, bytes memory _signature) public { bytes32 _channelId = getChannelId(_identity); require(isChannelOpened(_channelId), "Hermes: channel has to be opened"); require(_amount >= _transactorFee, "Hermes: amount should be bigger than transactor fee"); Channel storage _channel = channels[_channelId]; require(_amount <= _channel.stake, "Hermes: can't withdraw more than the current stake"); // Verify signature _channel.lastUsedNonce = _channel.lastUsedNonce + 1; address _signer = keccak256(abi.encodePacked(STAKE_RETURN_PREFIX, getChainID(), _channelId, _amount, _transactorFee, _channel.lastUsedNonce)).recover(_signature); require(getChannelId(_signer) == _channelId, "Hermes: have to be signed by channel party"); uint256 _newStakeAmount = _channel.stake - _amount; require(_newStakeAmount == 0 || _newStakeAmount >= minStake, "Hermes: stake can't be less than required min stake"); // Update channel state _channel.stake = _newStakeAmount; totalStake = totalStake - _amount; // Pay transacor fee then withdraw the rest if (_transactorFee > 0) { token.transfer(msg.sender, _transactorFee); } address _beneficiary = registry.getBeneficiary(_identity); token.transfer(_beneficiary, _amount - _transactorFee); emit NewStake(_channelId, _newStakeAmount); } /* --------------------------------------------------------------------------------------------- */ // Hermes is in Emergency situation when its status is `Punishment`. function resolveEmergency() public { require(getStatus() == Status.Punishment, "Hermes: should be in punishment status"); // 0.04% of total channels amount per time unit uint256 _punishmentPerUnit = round(totalStake * PUNISHMENT_PERCENT, 100) / 100; // No punishment during first time unit uint256 _unit = getUnitTime(); uint256 _timePassed = block.timestamp - punishment.activationBlockTime; uint256 _punishmentUnits = round(_timePassed, _unit) / _unit - 1; uint256 _punishmentAmount = _punishmentUnits * _punishmentPerUnit; punishment.amount = punishment.amount + _punishmentAmount; // XXX alternativelly we could send tokens into BlackHole (0x0000000...) uint256 _shouldHave = minimalExpectedBalance() + maxStake; // hermes should have funds for at least one maxStake settlement uint256 _currentBalance = token.balanceOf(address(this)); // If there are not enough available funds, they have to be topuped from msg.sender. if (_currentBalance < _shouldHave) { token.transferFrom(msg.sender, address(this), _shouldHave - _currentBalance); } // Disable punishment mode status = Status.Active; emit HermesPunishmentDeactivated(); } function getUnitTime() internal pure virtual returns (uint256) { return UNIT_SECONDS; } function setMinStake(uint256 _newMinStake) public onlyOwner { require(isHermesActive(), "Hermes: has to be active"); require(_newMinStake < maxStake, "Hermes: minStake has to be smaller than maxStake"); minStake = _newMinStake; emit MinStakeValueUpdated(_newMinStake); } function setMaxStake(uint256 _newMaxStake) public onlyOwner { require(isHermesActive(), "Hermes: has to be active"); require(_newMaxStake > minStake, "Hermes: maxStake has to be bigger than minStake"); maxStake = _newMaxStake; emit MaxStakeValueUpdated(_newMaxStake); } function setHermesFee(uint16 _newFee) public onlyOwner { require(getStatus() != Status.Closed, "Hermes: should be not closed"); require(_newFee <= 5000, "Hermes: fee can't be bigger than 50%"); require(block.timestamp >= lastFee.validFrom, "Hermes: can't update inactive fee"); // New fee will start be valid after delay time will pass uint64 _validFrom = uint64(getTimelock()); previousFee = lastFee; lastFee = HermesFee(_newFee, _validFrom); emit HermesFeeUpdated(_newFee, _validFrom); } function increaseHermesStake(uint256 _additionalStake) public onlyOwner { if (availableBalance() < _additionalStake) { uint256 _diff = _additionalStake - availableBalance(); token.transferFrom(msg.sender, address(this), _diff); } hermesStake = hermesStake + _additionalStake; emit HermesStakeIncreased(hermesStake); } // Hermes's available funds withdrawal. Can be done only if hermes is not closed and not in punishment mode. // Hermes can't withdraw stake, locked in channel funds and funds lended to him. function withdraw(address _beneficiary, uint256 _amount) public onlyOwner { require(isHermesActive(), "Hermes: have to be active"); require(availableBalance() >= _amount, "Hermes: should be enough funds available to withdraw"); token.transfer(_beneficiary, _amount); emit FundsWithdrawned(_amount, _beneficiary); } // Returns funds amount not locked in any channel, not staked and not lended from providers. function availableBalance() public view returns (uint256) { uint256 _totalLockedAmount = minimalExpectedBalance(); uint256 _currentBalance = token.balanceOf(address(this)); if (_totalLockedAmount > _currentBalance) { return uint256(0); } return _currentBalance - _totalLockedAmount; } // Returns true if channel is opened. function isChannelOpened(bytes32 _channelId) public view returns (bool) { return channels[_channelId].settled != 0 || channels[_channelId].stake != 0; } // If Hermes is not closed and is not in punishment mode, he is active. function isHermesActive() public view returns (bool) { Status _status = getStatus(); return _status != Status.Punishment && _status != Status.Closed; } function pauseChannelOpening() public onlyOperator { require(getStatus() == Status.Active, "Hermes: have to be in active state"); status = Status.Paused; emit ChannelOpeningPaused(); } function activateChannelOpening() public onlyOperator { require(getStatus() == Status.Paused, "Hermes: have to be in paused state"); status = Status.Active; emit ChannelOpeningActivated(); } function closeHermes() public onlyOwner { require(isHermesActive(), "Hermes: should be active"); status = Status.Closed; closingTimelock = getEmergencyTimelock(); emit HermesClosed(block.timestamp); } function getStakeBack(address _beneficiary) public onlyOwner { require(getStatus() == Status.Closed, "Hermes: have to be closed"); require(block.timestamp > closingTimelock, "Hermes: timelock period should be already passed"); uint256 _amount = token.balanceOf(address(this)) - punishment.amount; token.transfer(_beneficiary, _amount); } /* ------------------------------------------ HELPERS ------------------------------------------ */ // Returns timestamp until which exit request should be locked function getTimelock() internal view virtual returns (uint256) { return block.timestamp + DELAY_SECONDS; } function calculateHermesFee(uint256 _amount) public view returns (uint256) { return round((_amount * getActiveFee() / 100), 100) / 100; } // Funds which always have to be holded in hermes smart contract. function minimalExpectedBalance() public view returns (uint256) { return max(hermesStake, punishment.amount) + totalStake; } function getEmergencyTimelock() internal view virtual returns (uint256) { return block.timestamp + DELAY_SECONDS * 100; // 300 days } function validatePromise(bytes32 _channelId, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public view returns (bool) { bytes32 _hashlock = keccak256(abi.encodePacked(_preimage)); address _signer = keccak256(abi.encodePacked(getChainID(), _channelId, _amount, _transactorFee, _hashlock)).recover(_signature); return _signer == operator; } }
Funds which always have to be holded in hermes smart contract.
function minimalExpectedBalance() public view returns (uint256) { return max(hermesStake, punishment.amount) + totalStake; }
15,090,118
[ 1, 42, 19156, 1492, 3712, 1240, 358, 506, 366, 355, 785, 316, 366, 1035, 281, 13706, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16745, 6861, 13937, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 943, 12, 76, 1035, 281, 510, 911, 16, 293, 318, 1468, 475, 18, 8949, 13, 397, 2078, 510, 911, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-11-26 */ // File @openzeppelin/contracts/math/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @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); } 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); } } } } // File @openzeppelin/contracts-upgradeable/proxy/[email protected] // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @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 ); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @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.4._ */ 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.4._ */ 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); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @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" ); } } } // File contracts/ArcMasterChef.sol //** Arc MasterChef Contract */ //** Author [email protected] : Arc Finance 2022.02 */ //** Author [email protected] : Arc Finance 2022.02 */ //** Version 2.0.0 */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract ArcMasterChef is OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardLockedUp; // Reward locked up. uint256 nextHarvestUntil; // When can the user harvest again. // // We do some fancy math here. Basically, any point in time, the amount of Arcs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accArcPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accArcPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Arcs to distribute per block. uint256 lastRewardBlock; // Last block number that Arcs distribution occurs. uint256 accArcPerShare; // Accumulated Arcs per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points uint256 harvestInterval; // Harvest interval in seconds } // The Arc TOKEN! IERC20 public arc; // Deposit Fee address address public feeAddress; // Reward tokens holder address address public rewardHolder; // Arcs tokens created per block. 0.5 Arc per block. 10% to arc charity ( address ) uint256 public arcPerBlock; // Bonus muliplier for early arc makers. uint256 public constant BONUS_MULTIPLIER = 1; // Max harvest interval: 14 days. uint256 public constant MAXIMUM_HARVEST_INTERVAL = 10 days; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when Arcs mining starts. uint256 public startBlock; // Total locked up rewards uint256 public totalLockedUpRewards; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Compound(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event EmissionRateUpdated( address indexed caller, uint256 previousAmount, uint256 newAmount ); event RewardLockedUp( address indexed user, uint256 indexed pid, uint256 amountLockedUp ); function initialize( address _arc, // art token address address _feeAddress, // ? address _rewardHolder, // ? uint256 _startBlock, // ? uint256 _arcPerBlock // ? reward per block ) public initializer { arc = IERC20(_arc); rewardHolder = _rewardHolder; startBlock = _startBlock; arcPerBlock = _arcPerBlock; feeAddress = _feeAddress; totalAllocPoint = 0; __Ownable_init(); __ReentrancyGuard_init(); } // eth-arc pool // arc pool function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate ) public onlyOwner { require(_depositFeeBP <= 500, "add: invalid deposit fee basis points"); require( _harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "add: invalid harvest interval" ); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accArcPerShare: 0, depositFeeBP: _depositFeeBP, harvestInterval: _harvestInterval }) ); } // Update the given pool's Arcs allocation point and deposit fee. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate ) public onlyOwner { require(_depositFeeBP <= 500, "set: invalid deposit fee basis points"); require( _harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: invalid harvest interval" ); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; poolInfo[_pid].harvestInterval = _harvestInterval; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending Arcs on frontend. function pendingArc(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accArcPerShare = pool.accArcPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 arcReward = multiplier .mul(arcPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accArcPerShare = accArcPerShare.add( arcReward.mul(1e12).div(lpSupply) ); } uint256 pending = user.amount.mul(accArcPerShare).div(1e12).sub( user.rewardDebt ); return pending.add(user.rewardLockedUp); } // View function to see if user can harvest Arcs. function canHarvest(uint256 _pid, address _user) public view returns (bool) { UserInfo storage user = userInfo[_pid][_user]; return block.timestamp >= user.nextHarvestUntil; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 arcReward = multiplier .mul(arcPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); pool.accArcPerShare = pool.accArcPerShare.add( arcReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Arcs allocation. function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); payOrLockupPendingArc(_pid); if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); } else { user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accArcPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); payOrLockupPendingArc(_pid); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accArcPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Compound tokens to Arc pool. function compound(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require( address(pool.lpToken) == address(arc), "compound: not able to compound" ); updatePool(_pid); uint256 pending = user.amount.mul(pool.accArcPerShare).div(1e12).sub( user.rewardDebt ); safeArcTransferFrom(rewardHolder, address(this), pending); user.amount = user.amount.add(pending); user.rewardDebt = user.amount.mul(pool.accArcPerShare).div(1e12); emit Compound(msg.sender, _pid, pending); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; user.rewardLockedUp = 0; user.nextHarvestUntil = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Pay or lockup pending Arcs. function payOrLockupPendingArc(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.nextHarvestUntil == 0) { user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval); } uint256 pending = user.amount.mul(pool.accArcPerShare).div(1e12).sub( user.rewardDebt ); if (canHarvest(_pid, msg.sender)) { if (pending > 0 || user.rewardLockedUp > 0) { uint256 totalRewards = pending.add(user.rewardLockedUp); // reset lockup totalLockedUpRewards = totalLockedUpRewards.sub( user.rewardLockedUp ); user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp.add( pool.harvestInterval ); // send rewards safeArcTransferFrom(rewardHolder, msg.sender, totalRewards); } } else if (pending > 0) { user.rewardLockedUp = user.rewardLockedUp.add(pending); totalLockedUpRewards = totalLockedUpRewards.add(pending); emit RewardLockedUp(msg.sender, _pid, pending); } } // Safe Arc transfer function, just in case if rounding error causes pool to not have enough arcs. function safeArcTransferFrom( address _from, address _to, uint256 _amount ) internal { uint256 arcBal = arc.balanceOf(rewardHolder); if (_amount > arcBal) { revert("Not enough balance"); } else { arc.transferFrom(_from, _to, _amount); } } function setFeeAddress(address _feeAddress) public { require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); require(_feeAddress != address(0), "setFeeAddress: ZERO"); feeAddress = _feeAddress; } function setRewardHolder(address _rewardHolder) public { require(msg.sender == rewardHolder, "setRewardHolder: FORBIDDEN"); require(_rewardHolder != address(0), "setRewardHolder: ZERO"); rewardHolder = _rewardHolder; } // Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all. function updateEmissionRate(uint256 _arcPerBlock) public onlyOwner { massUpdatePools(); emit EmissionRateUpdated(msg.sender, arcPerBlock, _arcPerBlock); arcPerBlock = _arcPerBlock; } }
Accumulated Arcs per share, times 1e12. See below.
uint256 accArcPerShare;
7,997,543
[ 1, 8973, 5283, 690, 1201, 2143, 1534, 7433, 16, 4124, 404, 73, 2138, 18, 2164, 5712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 4078, 14598, 2173, 9535, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x28e041cc0D451980BD2CC4Fa5aD47805a6E4F9F8/sources/browser/contracts/Vault.sol
The VLT token The circulating supply of the VLT token To handle receiving ETH payments
contract Vault is IVLTRecipient { using SafeMath for uint256; using Address for address; IERC20 public vlt; address public vltAddress; uint256 public circulatingSupply; receive() external payable {} constructor (address _vlt) public { vlt = IERC20(_vlt); vltAddress = _vlt; circulatingSupply = vlt.totalSupply(); } function getVaultETHBalance() public view returns (uint256) { return address(this).balance; } function getVaultVLTBalance() public view returns (uint256) { return vlt.balanceOf(address(this)); } function getCirculatingSupply() public view returns (uint256) { return circulatingSupply; } function tokenFallback(address payable _from, uint _value) public override returns (bool) { require(msg.sender == vltAddress, "Only vault token can call this function"); sendBackEth(_from, _value); return true; } function sendBackEth(address payable _from, uint256 _tokenAmount) internal { require(getVaultETHBalance() > 0, "Vault has no ETH"); uint256 tokenPerEth = getCirculatingSupply().div(getVaultETHBalance()); uint256 totalEth = _tokenAmount.div(tokenPerEth); address payable swapInitator = _from; swapInitator.transfer(totalEth); circulatingSupply = circulatingSupply.sub(_tokenAmount); } }
811,429
[ 1, 1986, 776, 12050, 1147, 1021, 5886, 1934, 1776, 14467, 434, 326, 776, 12050, 1147, 2974, 1640, 15847, 512, 2455, 25754, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17329, 353, 21602, 12050, 18241, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 5267, 364, 1758, 31, 203, 203, 225, 467, 654, 39, 3462, 1071, 331, 5618, 31, 203, 225, 1758, 1071, 331, 5618, 1887, 31, 203, 203, 225, 2254, 5034, 1071, 5886, 1934, 1776, 3088, 1283, 31, 203, 21281, 203, 203, 225, 6798, 1435, 3903, 8843, 429, 2618, 203, 225, 3885, 261, 2867, 389, 90, 5618, 13, 1071, 288, 203, 565, 331, 5618, 273, 467, 654, 39, 3462, 24899, 90, 5618, 1769, 203, 565, 331, 5618, 1887, 273, 389, 90, 5618, 31, 203, 565, 5886, 1934, 1776, 3088, 1283, 273, 331, 5618, 18, 4963, 3088, 1283, 5621, 203, 225, 289, 203, 21281, 225, 445, 11031, 3714, 1584, 44, 13937, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 1758, 12, 2211, 2934, 12296, 31, 203, 225, 289, 203, 203, 225, 445, 11031, 3714, 58, 12050, 13937, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 331, 5618, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 225, 289, 203, 203, 225, 445, 1927, 481, 1934, 1776, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 5886, 1934, 1776, 3088, 1283, 31, 203, 225, 289, 203, 203, 225, 445, 1147, 12355, 12, 2867, 8843, 429, 389, 2080, 16, 2254, 389, 1132, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 331, 5618, 1887, 16, 315, 3386, 9229, 1147, 848, 745, 2 ]
./full_match/3/0xbEdb644b722Aa0d40BE1e47058BBE16047B99f17/sources/browser/Woolf.sol
mint price max number of tokens that can be minted - 50000 in production number of tokens that can be claimed for free - 20% of MAX_TOKENS number of tokens have been minted so far mapping from tokenId to a struct containing the token's traits mapping from hashed(tokenTrait) to the tokenId it's associated with used to ensure there are no duplicates list of probabilities for each trait type 0 - 9 are associated with Ape, 10 - 18 are associated with Wolves list of aliases for Walker's Alias algorithm 0 - 9 are associated with Ape, 10 - 18 are associated with Wolves reference to the Barn for choosing random Wolf thieves reference to $MutantPeach for burning on mint reference to Traits
contract Woolf is IWoolf, ERC721Enumerable, Ownable, Pausable { ISuperShibaBAMC public bamc; ISuperShibaClub public club; uint256 public MINT_PRICE = 0.002 ether; uint256 public immutable MAX_TOKENS; uint256 public PAID_TOKENS; uint16 public minted = 0; mapping(uint256 => ApeWolf) public tokenTraits; mapping(uint256 => uint256) public existingCombinations; mapping(uint256 => address) public superShibaBAMCTokensMint; mapping(uint256 => address) public superShibaClubTokensMint; uint8[][18] public rarities; uint8[][18] public aliases; IBarn public barn; MutantPeach public mutantPeach; ITraits public traits; address private wolfGameTreasury; constructor(address _peach, address _traits, uint256 _maxTokens, address _superShibaBAMC, address _superShibaClub) ERC721("Wolf Game", 'WGAME') { mutantPeach = MutantPeach(_peach); traits = ITraits(_traits); MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; bamc = ISuperShibaBAMC(_superShibaBAMC); club = ISuperShibaClub(_superShibaClub); rarities[0] = [15, 50, 200, 250, 255]; aliases[0] = [4, 4, 4, 4, 4]; rarities[1] = [190, 215, 240, 100, 110, 135, 160, 185, 80, 210, 235, 240, 80, 80, 100, 100, 100, 245, 250, 255]; aliases[1] = [1, 2, 4, 0, 5, 6, 7, 9, 0, 10, 11, 17, 0, 0, 0, 0, 4, 18, 19, 19]; rarities[2] = [255, 30, 60, 60, 150, 156]; aliases[2] = [0, 0, 0, 0, 0, 0]; rarities[3] = [221, 100, 181, 140, 224, 147, 84, 228, 140, 224, 250, 160, 241, 207, 173, 84, 254, 220, 196, 140, 168, 252, 140, 183, 236, 252, 224, 255]; aliases[3] = [1, 2, 5, 0, 1, 7, 1, 10, 5, 10, 11, 12, 13, 14, 16, 11, 17, 23, 13, 14, 17, 23, 23, 24, 27, 27, 27, 27]; rarities[4] = [175, 100, 40, 250, 115, 100, 185, 175, 180, 255]; aliases[4] = [3, 0, 4, 6, 6, 7, 8, 8, 9, 9]; rarities[5] = [80, 225, 227, 228, 112, 240, 64, 160, 167, 217, 171, 64, 240, 126, 80, 255]; aliases[5] = [1, 2, 3, 8, 2, 8, 8, 9, 9, 10, 13, 10, 13, 15, 13, 15]; rarities[6] = [255]; aliases[6] = [0]; rarities[7] = [243, 189, 133, 133, 57, 95, 152, 135, 133, 57, 222, 168, 57, 57, 38, 114, 114, 114, 255]; aliases[7] = [1, 7, 0, 0, 0, 0, 0, 10, 0, 0, 11, 18, 0, 0, 0, 1, 7, 11, 18]; rarities[8] = [255]; aliases[8] = [0]; rarities[9] = [210, 90, 9, 9, 9, 150, 9, 255, 9]; aliases[9] = [5, 0, 0, 5, 5, 7, 5, 7, 5]; rarities[10] = [255]; aliases[10] = [0]; rarities[11] = [255]; aliases[11] = [0]; rarities[12] = [135, 177, 219, 141, 183, 225, 147, 189, 231, 135, 135, 135, 135, 246, 150, 150, 156, 165, 171, 180, 186, 195, 201, 210, 243, 252, 255]; aliases[12] = [1, 2, 3, 4, 5, 6, 7, 8, 13, 3, 6, 14, 15, 16, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 26, 26]; rarities[13] = [255]; aliases[13] = [0]; rarities[14] = [239, 244, 249, 234, 234, 234, 234, 234, 234, 234, 130, 255, 247]; aliases[14] = [1, 2, 11, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11]; rarities[15] = [75, 180, 165, 120, 60, 150, 105, 195, 45, 225, 75, 45, 195, 120, 255]; aliases[15] = [1, 9, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 14, 12, 14]; rarities[16] = [255]; aliases[16] = [0]; rarities[17] = [8, 160, 73, 255]; aliases[17] = [2, 3, 3, 3]; } function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); require(msg.value == 0); } uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); _safeMint(address(barn), minted); tokenIds[i] = minted; } generate(minted, seed); totalWoolCost += mintCost(minted); } if (totalWoolCost > 0) mutantPeach.burn(_msgSender(), totalWoolCost); if (stake) barn.addManyToBarnAndPack(_msgSender(), tokenIds); } function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); require(msg.value == 0); } uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); _safeMint(address(barn), minted); tokenIds[i] = minted; } generate(minted, seed); totalWoolCost += mintCost(minted); } if (totalWoolCost > 0) mutantPeach.burn(_msgSender(), totalWoolCost); if (stake) barn.addManyToBarnAndPack(_msgSender(), tokenIds); } } else { uint256 totalWoolCost = 0; function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); require(msg.value == 0); } uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); _safeMint(address(barn), minted); tokenIds[i] = minted; } generate(minted, seed); totalWoolCost += mintCost(minted); } if (totalWoolCost > 0) mutantPeach.burn(_msgSender(), totalWoolCost); if (stake) barn.addManyToBarnAndPack(_msgSender(), tokenIds); } function mint(uint256 amount, bool stake) external payable whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); require(minted + amount <= MAX_TOKENS, "All tokens minted"); require(amount > 0 && amount <= 10, "Invalid mint amount"); if (minted < PAID_TOKENS) { require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold"); require(amount * MINT_PRICE == msg.value, "Invalid payment amount"); require(msg.value == 0); } uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); address recipient = selectRecipient(seed); if (!stake || recipient != _msgSender()) { _safeMint(recipient, minted); _safeMint(address(barn), minted); tokenIds[i] = minted; } generate(minted, seed); totalWoolCost += mintCost(minted); } if (totalWoolCost > 0) mutantPeach.burn(_msgSender(), totalWoolCost); if (stake) barn.addManyToBarnAndPack(_msgSender(), tokenIds); } } else { function freeMint(bool stake) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); uint256 bamcCount = bamc.balanceOf(msg.sender); uint256 clubCount = club.balanceOf(msg.sender); require(bamcCount > 0 || clubCount > 0, "Sorry, you don't have shiba"); uint256 mintCount = 0; for (uint256 i = 0; i < bamcCount; i++) { uint256 bamcTokenId = bamc.tokenOfOwnerByIndex(msg.sender, i); if (superShibaBAMCTokensMint[bamcTokenId] == address(0)) { mintCount++; superShibaBAMCTokensMint[bamcTokenId] = msg.sender; } } for (uint256 i = 0; i < clubCount; i++) { uint256 clubTokenId = club.tokenOfOwnerByIndex(msg.sender, i); if (superShibaClubTokensMint[clubTokenId] == address(0)) { mintCount++; superShibaClubTokensMint[clubTokenId] = msg.sender; } } _freeMint(mintCount, stake); } function freeMint(bool stake) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); uint256 bamcCount = bamc.balanceOf(msg.sender); uint256 clubCount = club.balanceOf(msg.sender); require(bamcCount > 0 || clubCount > 0, "Sorry, you don't have shiba"); uint256 mintCount = 0; for (uint256 i = 0; i < bamcCount; i++) { uint256 bamcTokenId = bamc.tokenOfOwnerByIndex(msg.sender, i); if (superShibaBAMCTokensMint[bamcTokenId] == address(0)) { mintCount++; superShibaBAMCTokensMint[bamcTokenId] = msg.sender; } } for (uint256 i = 0; i < clubCount; i++) { uint256 clubTokenId = club.tokenOfOwnerByIndex(msg.sender, i); if (superShibaClubTokensMint[clubTokenId] == address(0)) { mintCount++; superShibaClubTokensMint[clubTokenId] = msg.sender; } } _freeMint(mintCount, stake); } function freeMint(bool stake) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); uint256 bamcCount = bamc.balanceOf(msg.sender); uint256 clubCount = club.balanceOf(msg.sender); require(bamcCount > 0 || clubCount > 0, "Sorry, you don't have shiba"); uint256 mintCount = 0; for (uint256 i = 0; i < bamcCount; i++) { uint256 bamcTokenId = bamc.tokenOfOwnerByIndex(msg.sender, i); if (superShibaBAMCTokensMint[bamcTokenId] == address(0)) { mintCount++; superShibaBAMCTokensMint[bamcTokenId] = msg.sender; } } for (uint256 i = 0; i < clubCount; i++) { uint256 clubTokenId = club.tokenOfOwnerByIndex(msg.sender, i); if (superShibaClubTokensMint[clubTokenId] == address(0)) { mintCount++; superShibaClubTokensMint[clubTokenId] = msg.sender; } } _freeMint(mintCount, stake); } function freeMint(bool stake) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); uint256 bamcCount = bamc.balanceOf(msg.sender); uint256 clubCount = club.balanceOf(msg.sender); require(bamcCount > 0 || clubCount > 0, "Sorry, you don't have shiba"); uint256 mintCount = 0; for (uint256 i = 0; i < bamcCount; i++) { uint256 bamcTokenId = bamc.tokenOfOwnerByIndex(msg.sender, i); if (superShibaBAMCTokensMint[bamcTokenId] == address(0)) { mintCount++; superShibaBAMCTokensMint[bamcTokenId] = msg.sender; } } for (uint256 i = 0; i < clubCount; i++) { uint256 clubTokenId = club.tokenOfOwnerByIndex(msg.sender, i); if (superShibaClubTokensMint[clubTokenId] == address(0)) { mintCount++; superShibaClubTokensMint[clubTokenId] = msg.sender; } } _freeMint(mintCount, stake); } function freeMint(bool stake) external whenNotPaused { require(tx.origin == _msgSender(), "Only EOA"); uint256 bamcCount = bamc.balanceOf(msg.sender); uint256 clubCount = club.balanceOf(msg.sender); require(bamcCount > 0 || clubCount > 0, "Sorry, you don't have shiba"); uint256 mintCount = 0; for (uint256 i = 0; i < bamcCount; i++) { uint256 bamcTokenId = bamc.tokenOfOwnerByIndex(msg.sender, i); if (superShibaBAMCTokensMint[bamcTokenId] == address(0)) { mintCount++; superShibaBAMCTokensMint[bamcTokenId] = msg.sender; } } for (uint256 i = 0; i < clubCount; i++) { uint256 clubTokenId = club.tokenOfOwnerByIndex(msg.sender, i); if (superShibaClubTokensMint[clubTokenId] == address(0)) { mintCount++; superShibaClubTokensMint[clubTokenId] = msg.sender; } } _freeMint(mintCount, stake); } require(minted + mintCount <= MAX_TOKENS, "All tokens minted"); require(mintCount > 0, "The shiba in your wallet has been mint"); function _freeMint(uint256 amount, bool stake) private whenNotPaused { uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); if (!stake) { _safeMint(msg.sender, minted); _safeMint(address(barn), minted); tokenIds[i] = minted; } generate(minted, seed); } if (stake) barn.addManyToBarnAndPack(_msgSender(), tokenIds); } function _freeMint(uint256 amount, bool stake) private whenNotPaused { uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); if (!stake) { _safeMint(msg.sender, minted); _safeMint(address(barn), minted); tokenIds[i] = minted; } generate(minted, seed); } if (stake) barn.addManyToBarnAndPack(_msgSender(), tokenIds); } function _freeMint(uint256 amount, bool stake) private whenNotPaused { uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0); uint256 seed; for (uint i = 0; i < amount; i++) { minted++; seed = random(minted); if (!stake) { _safeMint(msg.sender, minted); _safeMint(address(barn), minted); tokenIds[i] = minted; } generate(minted, seed); } if (stake) barn.addManyToBarnAndPack(_msgSender(), tokenIds); } } else { function mintCost(uint256 tokenId) public view returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 20000 ether; if (tokenId <= MAX_TOKENS * 4 / 5) return 40000 ether; return 80000 ether; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { if (_msgSender() != address(barn)) require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function generate(uint256 tokenId, uint256 seed) internal returns (ApeWolf memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; return t; } return generate(tokenId, random(seed)); } function generate(uint256 tokenId, uint256 seed) internal returns (ApeWolf memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; return t; } return generate(tokenId, random(seed)); } function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); if (seed >> 8 < rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } function selectRecipient(uint256 seed) internal view returns (address) { if (thief == address(0x0)) return _msgSender(); return thief; } function selectTraits(uint256 seed) internal view returns (ApeWolf memory t) { t.isApe = (seed & 0xFFFF) % 10 != 0; uint8 shift = t.isApe ? 0 : 9; seed >>= 16; t.fur = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.head = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.ears = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.eyes = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.nose = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.mouth = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.neck = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; t.feet = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); } function structToHash(ApeWolf memory s) internal pure returns (uint256) { return uint256(bytes32( abi.encodePacked( s.isApe, s.fur, s.head, s.eyes, s.mouth, s.neck, s.ears, s.feet, s.alphaIndex ) )); } function getTokenTraits(uint256 tokenId) external view override returns (ApeWolf memory) { return tokenTraits[tokenId]; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } function setBarn(address _barn) external onlyOwner { barn = IBarn(_barn); } function setSuperShibaBAMCAddress(address _address) external onlyOwner { bamc = ISuperShibaBAMC(_address); } function setSuperShibaClubAddress(address _address) external onlyOwner { club = ISuperShibaClub(_address); } function withdraw() external onlyOwner { payable(wolfGameTreasury).transfer(address(this).balance); } function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function setMintPrice(uint256 _price) external onlyOwner { MINT_PRICE = _price; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return traits.tokenURI(tokenId); } function setTreasury(address _treasury) external onlyOwner { wolfGameTreasury = _treasury; } }
14,200,492
[ 1, 81, 474, 6205, 943, 1300, 434, 2430, 716, 848, 506, 312, 474, 329, 300, 1381, 2787, 316, 12449, 1300, 434, 2430, 716, 848, 506, 7516, 329, 364, 4843, 300, 4200, 9, 434, 4552, 67, 8412, 55, 1300, 434, 2430, 1240, 2118, 312, 474, 329, 1427, 10247, 2874, 628, 1147, 548, 358, 279, 1958, 4191, 326, 1147, 1807, 18370, 2874, 628, 14242, 12, 2316, 15525, 13, 358, 326, 1147, 548, 518, 1807, 3627, 598, 1399, 358, 3387, 1915, 854, 1158, 11211, 666, 434, 17958, 364, 1517, 13517, 618, 374, 300, 2468, 854, 3627, 598, 432, 347, 16, 1728, 300, 6549, 854, 3627, 598, 678, 355, 3324, 666, 434, 6900, 364, 7564, 264, 1807, 11873, 4886, 374, 300, 2468, 854, 3627, 598, 432, 347, 16, 1728, 300, 6549, 854, 3627, 598, 678, 355, 3324, 2114, 358, 326, 605, 1303, 364, 24784, 310, 2744, 678, 355, 74, 286, 1385, 3324, 2114, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 678, 1371, 74, 353, 467, 59, 1371, 74, 16, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 16, 21800, 16665, 288, 203, 225, 467, 8051, 1555, 495, 69, 38, 2192, 39, 1071, 11400, 71, 31, 203, 225, 467, 8051, 1555, 495, 69, 2009, 373, 1071, 927, 373, 31, 203, 203, 225, 2254, 5034, 1071, 490, 3217, 67, 7698, 1441, 273, 374, 18, 24908, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 11732, 4552, 67, 8412, 55, 31, 203, 225, 2254, 5034, 1071, 15662, 734, 67, 8412, 55, 31, 203, 225, 2254, 2313, 1071, 312, 474, 329, 273, 374, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 432, 347, 59, 355, 74, 13, 1071, 1147, 30370, 31, 203, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 2062, 24107, 1012, 31, 203, 203, 225, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 2240, 1555, 495, 69, 38, 2192, 1268, 3573, 49, 474, 31, 203, 225, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 2240, 1555, 495, 69, 2009, 373, 5157, 49, 474, 31, 203, 203, 225, 2254, 28, 63, 6362, 2643, 65, 1071, 436, 297, 1961, 31, 203, 225, 2254, 28, 63, 6362, 2643, 65, 1071, 6900, 31, 203, 203, 225, 23450, 1303, 1071, 324, 1303, 31, 203, 225, 14138, 970, 11227, 497, 1071, 4318, 970, 11227, 497, 31, 203, 225, 467, 30370, 1071, 18370, 31, 203, 203, 225, 1758, 3238, 341, 355, 74, 12496, 56, 266, 345, 22498, 31, 203, 203, 225, 3885, 12, 2867, 389, 347, 497, 16, 1758, 2 ]
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/_equilibria/root/number/types/UFixed18.sol
* @notice Returns whether unsigned fixed-decimal `a` is greater than `b` @param a First unsigned fixed-decimal @param b Second unsigned fixed-decimal @return Whether `a` is greater than `b`/
function gt(UFixed18 a, UFixed18 b) internal pure returns (bool) { return compare(a, b) == 2; }
1,912,947
[ 1, 1356, 2856, 9088, 5499, 17, 12586, 1375, 69, 68, 353, 6802, 2353, 1375, 70, 68, 225, 279, 5783, 9088, 5499, 17, 12586, 225, 324, 7631, 9088, 5499, 17, 12586, 327, 17403, 1375, 69, 68, 353, 6802, 2353, 1375, 70, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9879, 12, 57, 7505, 2643, 279, 16, 587, 7505, 2643, 324, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 3400, 12, 69, 16, 324, 13, 422, 576, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev A simple operator control base */ abstract contract OperatorGuard is Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _operators; /** * @dev Add an operator. * @param operator The operator to add. */ function addOperator(address operator) external onlyOwner { require(_operators.add(operator), "already an operator"); } /** * @dev Remove an operator. * @param operator The operator to remove. */ function removeOperator(address operator) external onlyOwner { require(_operators.remove(operator), "already an operator"); } /** * @dev Retrive all operators */ function operators() external view returns (address[] memory operators_) { uint256 count = _operators.length(); operators_ = new address[](count); for (uint256 index = 0; index < count; ++index) operators_[index] = _operators.at(index); } /** * @dev Modifier for minter allowance */ modifier onlyOperator() { require(_operators.contains(msg.sender), "require registred operator"); _; } }
* @dev Modifier for minter allowance/
modifier onlyOperator() { require(_operators.contains(msg.sender), "require registred operator"); _; }
1,796,047
[ 1, 9829, 364, 1131, 387, 1699, 1359, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5592, 1435, 288, 203, 3639, 2583, 24899, 30659, 18, 12298, 12, 3576, 18, 15330, 3631, 315, 6528, 960, 376, 1118, 3726, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens */ contract ERC721 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev Called by the owner to pause, triggers stopped state. */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev Called by the owner to unpause, returns to normal state. */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title CurioAuction * @dev CurioAuction contract implements clock auction for tokens sale. */ contract CurioAuction is Pausable { event AuctionCreated( uint256 indexed tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration ); event AuctionSuccessful( uint256 indexed tokenId, uint256 totalPrice, address indexed winner ); event AuctionCancelled(uint256 indexed tokenId); // Represents an auction on a token struct Auction { // Current owner of token address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started (0 if this auction has been concluded) uint64 startedAt; } // Check that this contract is correct for Curio main contract bool public isCurioAuction = true; // Reference to token contract ERC721 public tokenContract; // Value of fee (1/100 of a percent; 0-10,000 map to 0%-100%) uint256 public feePercent; // Map from token ID to auction mapping (uint256 => Auction) tokenIdToAuction; // Count of release tokens sold by auction uint256 public releaseTokensSaleCount; // Limit of start and end prices in wei uint256 public auctionPriceLimit; /** * @dev Constructor function * @param _tokenAddress Address of ERC721 token contract (Curio core contract) * @param _fee Percent of fee (0-10,000) * @param _auctionPriceLimit Limit of start and end price in auction (in wei) */ constructor( address _tokenAddress, uint256 _fee, uint256 _auctionPriceLimit ) public { require(_fee <= 10000); feePercent = _fee; ERC721 candidateContract = ERC721(_tokenAddress); require(candidateContract.implementsERC721()); tokenContract = candidateContract; require(_auctionPriceLimit == uint256(uint128(_auctionPriceLimit))); auctionPriceLimit = _auctionPriceLimit; } // ----------------------------------------- // External interface // ----------------------------------------- /** * @dev Creates a new auction. * @param _tokenId ID of token to auction, sender must be owner * @param _startingPrice Price of item (in wei) at beginning of auction * @param _endingPrice Price of item (in wei) at end of auction * @param _duration Length of auction (in seconds) * @param _seller Seller address */ function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) whenNotPaused external { // Overflow and limitation input check require(_startingPrice == uint256(uint128(_startingPrice))); require(_startingPrice < auctionPriceLimit); require(_endingPrice == uint256(uint128(_endingPrice))); require(_endingPrice < auctionPriceLimit); require(_duration == uint256(uint64(_duration))); // Check call from token contract require(msg.sender == address(tokenContract)); // Transfer token from seller to this contract _deposit(_seller, _tokenId); // Create an auction Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Returns auction info for a token on auction. * @param _tokenId ID of token on auction */ function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { // Check token on auction Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /** * @dev Returns the current price of an auction. * @param _tokenId ID of the token price we are checking */ function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { // Check token on auction Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } /** * @dev Bids on an open auction, completing the auction and transferring * ownership of the token if enough Ether is supplied. * @param _tokenId ID of token to bid on */ function bid(uint256 _tokenId) external payable whenNotPaused { address seller = tokenIdToAuction[_tokenId].seller; // Check auction conditions and transfer Ether to seller // _bid verifies token ID size _bid(_tokenId, msg.value); // Transfer token from this contract to msg.sender after successful bid _transfer(msg.sender, _tokenId); // If seller is tokenContract then increase counter of release tokens if (seller == address(tokenContract)) { releaseTokensSaleCount++; } } /** * @dev Cancels an auction. Returns the token to original owner. * This is a state-modifying function that can * be called while the contract is paused. * @param _tokenId ID of token on auction */ function cancelAuction(uint256 _tokenId) external { // Check token on auction Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); // Check sender as seller address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /** * @dev Cancels an auction when the contract is paused. Only owner. * Returns the token to seller. This should only be used in emergencies. * @param _tokenId ID of the NFT on auction to cancel */ function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { // Check token on auction Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /** * @dev Withdraw all Ether (fee) from auction contract to token contract. * Only auction contract owner. */ function withdrawBalance() external { address tokenAddress = address(tokenContract); // Check sender as owner or token contract require(msg.sender == owner || msg.sender == tokenAddress); // Send Ether on this contract to token contract // Boolean method make sure that even if one fails it will still work bool res = tokenAddress.send(address(this).balance); } /** * @dev Set new auction price limit. * @param _newAuctionPriceLimit Start and end price limit */ function setAuctionPriceLimit(uint256 _newAuctionPriceLimit) external { address tokenAddress = address(tokenContract); // Check sender as owner or token contract require(msg.sender == owner || msg.sender == tokenAddress); // Check overflow require(_newAuctionPriceLimit == uint256(uint128(_newAuctionPriceLimit))); // Set new auction price limit auctionPriceLimit = _newAuctionPriceLimit; } // ----------------------------------------- // Internal interface // ----------------------------------------- /** * @dev Returns true if the claimant owns the token. * @param _claimant Address claiming to own the token * @param _tokenId ID of token whose ownership to verify */ function _owns( address _claimant, uint256 _tokenId ) internal view returns (bool) { return (tokenContract.ownerOf(_tokenId) == _claimant); } /** * @dev Transfer token from owner to this contract. * @param _owner Current owner address of token to escrow * @param _tokenId ID of token whose approval to verify */ function _deposit( address _owner, uint256 _tokenId ) internal { tokenContract.transferFrom(_owner, this, _tokenId); } /** * @dev Transfers token owned by this contract to another address. * Returns true if the transfer succeeds. * @param _receiver Address to transfer token to * @param _tokenId ID of token to transfer */ function _transfer( address _receiver, uint256 _tokenId ) internal { tokenContract.transfer(_receiver, _tokenId); } /** * @dev Adds an auction to the list of open auctions. * @param _tokenId The ID of the token to be put on auction * @param _auction Auction to add */ function _addAuction( uint256 _tokenId, Auction _auction ) internal { // Require that all auctions have a duration of at least one minute. require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /** * @dev Removes an auction from the list of open auctions. * @param _tokenId ID of token on auction */ function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /** * @dev Remove an auction and transfer token from this contract to seller address. * @param _tokenId The ID of the token * @param _seller Seller address */ function _cancelAuction( uint256 _tokenId, address _seller ) internal { // Remove auction from list _removeAuction(_tokenId); // Transfer token to seller _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /** * @dev Check token is on auction. * @param _auction Auction to check */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /** * @dev Calculates fee of a sale. * @param _price Token price */ function _calculateFee(uint256 _price) internal view returns (uint256) { return _price * feePercent / 10000; } /** * @dev Returns current price of a token on auction. * @param _auction Auction for calculate current price */ function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // Check that auction were started // Variable secondsPassed is positive if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _calculateCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /** * @dev Calculate the current price of an auction. * @param _startingPrice Price of item (in wei) at beginning of auction * @param _endingPrice Price of item (in wei) at end of auction * @param _duration Length of auction (in seconds) * @param _secondsPassed Seconds passed after auction start */ function _calculateCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { if (_secondsPassed >= _duration) { // The auction lasts longer duration // Return end price return _endingPrice; } else { // totalPriceChange can be negative int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /** * @dev Calculate auction price and transfers winnings. Does NOT transfer ownership of token. * @param _tokenId The ID of the token * @param _bidAmount Amount (in wei) offered for auction */ function _bid( uint256 _tokenId, uint256 _bidAmount ) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; // Check that this auction is currently live require(_isOnAuction(auction)); // Check that the incoming bid is higher than the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); // Transfer proceeds to seller if (price > 0) { uint256 fee = _calculateFee(price); uint256 sellerProceeds = price - fee; // Transfer proceeds to seller seller.transfer(sellerProceeds); } // Calculate excess funds and transfer it back to bidder uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } }
* @dev Returns true if the claimant owns the token. @param _claimant Address claiming to own the token @param _tokenId ID of token whose ownership to verify/
function _owns( address _claimant, uint256 _tokenId ) internal view returns (bool) { return (tokenContract.ownerOf(_tokenId) == _claimant); }
6,443,590
[ 1, 1356, 638, 309, 326, 7516, 970, 29065, 326, 1147, 18, 225, 389, 14784, 970, 5267, 7516, 310, 358, 4953, 326, 1147, 225, 389, 2316, 548, 1599, 434, 1147, 8272, 23178, 358, 3929, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 995, 87, 12, 203, 565, 1758, 389, 14784, 970, 16, 203, 565, 2254, 5034, 389, 2316, 548, 203, 225, 262, 203, 565, 2713, 203, 565, 1476, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 327, 261, 2316, 8924, 18, 8443, 951, 24899, 2316, 548, 13, 422, 389, 14784, 970, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x7a3a47f6dC4B53B50E06960CC7c081D8332b29a0/sources/Gravity.sol
The block number when MILK2 mining starts.
uint256 public startFirstPhaseBlock;
3,308,774
[ 1, 1986, 1203, 1300, 1347, 490, 2627, 47, 22, 1131, 310, 2542, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 787, 3759, 11406, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xaF947D3C15168ED5eE667BD69446D4c26a63BfE1/sources/browser/lasttry.sol
* @dev {ERC20} token, including: - ability for holders to burn (destroy) their tokens - a minter role that allows for token minting (creation) - a pauser role that allows to stop all token transfers This contract uses {AccessControl} to lock permissioned functions using the different roles - head to its documentation for details. The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role, which will let it grant both minter and pauser roles to other accounts./
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Pausable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
793,954
[ 1, 95, 654, 39, 3462, 97, 1147, 16, 6508, 30, 225, 300, 7123, 364, 366, 4665, 358, 18305, 261, 11662, 13, 3675, 2430, 225, 300, 279, 1131, 387, 2478, 716, 5360, 364, 1147, 312, 474, 310, 261, 17169, 13, 225, 300, 279, 6790, 1355, 2478, 716, 5360, 358, 2132, 777, 1147, 29375, 1220, 6835, 4692, 288, 16541, 97, 358, 2176, 4132, 329, 4186, 1450, 326, 3775, 4900, 300, 910, 358, 2097, 7323, 364, 3189, 18, 1021, 2236, 716, 5993, 383, 1900, 326, 6835, 903, 506, 17578, 326, 1131, 387, 471, 6790, 1355, 4900, 16, 487, 5492, 487, 326, 805, 3981, 2478, 16, 1492, 903, 2231, 518, 7936, 3937, 1131, 387, 471, 6790, 1355, 4900, 358, 1308, 9484, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 18385, 49, 2761, 16507, 1355, 353, 1772, 16, 24349, 16, 4232, 39, 3462, 16507, 16665, 288, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 4232, 39, 3462, 12, 529, 16, 3273, 13, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 11722, 1435, 1071, 5024, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 315, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 30, 1297, 1240, 6790, 1355, 2478, 358, 11722, 8863, 203, 3639, 389, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 640, 19476, 1435, 1071, 5024, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 315, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 30, 1297, 1240, 6790, 1355, 2478, 358, 640, 19476, 8863, 203, 3639, 389, 318, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 5024, 3849, 12, 654, 39, 3462, 16507, 16665, 13, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 565, 289, 2 ]
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.7.0; /** * @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); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.7.0; /** * @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; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.7.0; /** * @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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.7.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.7.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.7.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.7.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } // File: contracts/xDFIE.sol pragma solidity ^0.7.0; /** * @title TokenRecover * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } contract xDFIE is ERC20Capped, ERC20Burnable, TokenRecover { // indicates if minting is finished bool private _mintingFinished = false; // indicates if transfer is enabled bool private _transferEnabled = false; /** * @dev Emitted during finish minting */ event MintFinished(); /** * @dev Emitted during transfer enabling */ event TransferEnabled(); /** * @dev Tokens can be minted only before minting finished. */ modifier canMint() { require(!_mintingFinished, "xDFIE: minting is finished"); _; } /** * @dev Tokens can be moved only after if transfer enabled or if you are an approved operator. */ modifier canTransfer(address from) { require( _transferEnabled , "xDFIE: transfer is not enabled or from does not have the OPERATOR role" ); _; } /** */ constructor() ERC20Capped(3e8 * (uint256(10) ** 18)) ERC20("xDFIE Token", "xDFIe") { uint8 decimals = 18; uint256 cap = 3e8 * (uint256(10) ** 18); uint256 initialSupply = 3e8 * (uint256(10) ** 18); bool transferEnabled = true; bool mintingFinished = true; require( mintingFinished == false || cap == initialSupply, "xDFIE: if finish minting, cap must be equal to initialSupply" ); _setupDecimals(decimals); if (initialSupply > 0) { _mint(owner(), initialSupply); } if (mintingFinished) { finishMinting(); } if (transferEnabled) { enableTransfer(); } } /** * @return if minting is finished or not. */ function mintingFinished() public view returns (bool) { return _mintingFinished; } /** * @return if transfer is enabled or not. */ function transferEnabled() public view returns (bool) { return _transferEnabled; } /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens * @param value The amount of tokens to mint */ function mint(address to, uint256 value) public canMint { _mint(to, value); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to * @param value The amount to be transferred * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) public virtual override(ERC20) canTransfer(_msgSender()) returns (bool) { return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another. * @param from The address which you want to send tokens from * @param to The address which you want to transfer to * @param value the amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) public virtual override(ERC20) canTransfer(from) returns (bool) { return super.transferFrom(from, to, value); } /** * @dev Function to stop minting new tokens. */ function finishMinting() public canMint onlyOwner { _mintingFinished = true; emit MintFinished(); } /** * @dev Function to enable transfers. */ function enableTransfer() public onlyOwner { _transferEnabled = true; emit TransferEnabled(); } /** * @dev See {ERC20-_beforeTokenTransfer}. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Capped) { super._beforeTokenTransfer(from, to, amount); } }
* @return if transfer is enabled or not./
function transferEnabled() public view returns (bool) { return _transferEnabled; }
411,258
[ 1, 2463, 309, 7412, 353, 3696, 578, 486, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1526, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 13866, 1526, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier:MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IWalletFactory.sol"; import "../interfaces/IRelayVerifier.sol"; import "../interfaces/ITokenHandler.sol"; import "../interfaces/EnvelopingTypes.sol"; /* solhint-disable no-inline-assembly */ /* solhint-disable avoid-low-level-calls */ /** * A verifier for relay transactions. */ contract RelayVerifier is IRelayVerifier, ITokenHandler, Ownable { using SafeMath for uint256; address private factory; constructor(address walletFactory) public { factory = walletFactory; } function versionVerifier() external override virtual view returns (string memory){ return "[email protected]"; } mapping (address => bool) public tokens; address[] public acceptedTokens; /* solhint-disable no-unused-vars */ function verifyRelayedCall( EnvelopingTypes.RelayRequest calldata relayRequest, bytes calldata signature ) external override virtual returns (bytes memory context) { require(tokens[relayRequest.request.tokenContract], "Token contract not allowed"); address payer = relayRequest.relayData.callForwarder; if(relayRequest.request.tokenContract != address(0)){ require(relayRequest.request.tokenAmount <= IERC20(relayRequest.request.tokenContract).balanceOf(payer), "balance too low"); } // Check for the codehash of the smart wallet sent bytes32 smartWalletCodeHash; assembly { smartWalletCodeHash := extcodehash(payer) } require(IWalletFactory(factory).runtimeCodeHash() == smartWalletCodeHash, "SW different to template"); return (abi.encode(payer, relayRequest.request.tokenAmount, relayRequest.request.tokenContract)); } function acceptToken(address token) external onlyOwner { require(token != address(0), "Token cannot be zero address"); require(tokens[token] == false, "Token is already accepted"); tokens[token] = true; acceptedTokens.push(token); } function getAcceptedTokens() external override view returns (address[] memory){ return acceptedTokens; } function acceptsToken(address token) external override view returns (bool){ return tokens[token]; } }
* A verifier for relay transactions./
contract RelayVerifier is IRelayVerifier, ITokenHandler, Ownable { using SafeMath for uint256; address private factory; pragma solidity ^0.6.12; constructor(address walletFactory) public { factory = walletFactory; } function versionVerifier() external override virtual view returns (string memory){ return "[email protected]"; } mapping (address => bool) public tokens; address[] public acceptedTokens; function verifyRelayedCall( EnvelopingTypes.RelayRequest calldata relayRequest, bytes calldata signature ) external override virtual returns (bytes memory context) { require(tokens[relayRequest.request.tokenContract], "Token contract not allowed"); address payer = relayRequest.relayData.callForwarder; if(relayRequest.request.tokenContract != address(0)){ require(relayRequest.request.tokenAmount <= IERC20(relayRequest.request.tokenContract).balanceOf(payer), "balance too low"); } require(IWalletFactory(factory).runtimeCodeHash() == smartWalletCodeHash, "SW different to template"); return (abi.encode(payer, relayRequest.request.tokenAmount, relayRequest.request.tokenContract)); } function verifyRelayedCall( EnvelopingTypes.RelayRequest calldata relayRequest, bytes calldata signature ) external override virtual returns (bytes memory context) { require(tokens[relayRequest.request.tokenContract], "Token contract not allowed"); address payer = relayRequest.relayData.callForwarder; if(relayRequest.request.tokenContract != address(0)){ require(relayRequest.request.tokenAmount <= IERC20(relayRequest.request.tokenContract).balanceOf(payer), "balance too low"); } require(IWalletFactory(factory).runtimeCodeHash() == smartWalletCodeHash, "SW different to template"); return (abi.encode(payer, relayRequest.request.tokenAmount, relayRequest.request.tokenContract)); } bytes32 smartWalletCodeHash; assembly { smartWalletCodeHash := extcodehash(payer) } function acceptToken(address token) external onlyOwner { require(token != address(0), "Token cannot be zero address"); require(tokens[token] == false, "Token is already accepted"); tokens[token] = true; acceptedTokens.push(token); } function getAcceptedTokens() external override view returns (address[] memory){ return acceptedTokens; } function acceptsToken(address token) external override view returns (bool){ return tokens[token]; } }
2,565,249
[ 1, 37, 20130, 364, 18874, 8938, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4275, 528, 17758, 353, 467, 27186, 17758, 16, 467, 1345, 1503, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 3238, 3272, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 31, 203, 203, 565, 3885, 12, 2867, 9230, 1733, 13, 1071, 288, 203, 3639, 3272, 273, 9230, 1733, 31, 203, 565, 289, 203, 203, 565, 445, 1177, 17758, 1435, 3903, 3849, 5024, 1476, 1135, 261, 1080, 3778, 15329, 203, 3639, 327, 315, 86, 430, 18, 275, 8250, 310, 18, 2316, 18, 1667, 1251, 36, 22, 18, 20, 18, 21, 14432, 203, 565, 289, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 2430, 31, 203, 565, 1758, 8526, 1071, 8494, 5157, 31, 203, 203, 565, 445, 3929, 27186, 329, 1477, 12, 203, 3639, 1374, 8250, 310, 2016, 18, 27186, 691, 745, 892, 18874, 691, 16, 203, 3639, 1731, 745, 892, 3372, 203, 565, 262, 203, 565, 3903, 203, 565, 3849, 203, 565, 5024, 203, 565, 1135, 261, 3890, 3778, 819, 13, 288, 203, 3639, 2583, 12, 7860, 63, 2878, 528, 691, 18, 2293, 18, 2316, 8924, 6487, 315, 1345, 6835, 486, 2935, 8863, 203, 203, 3639, 1758, 293, 1773, 273, 18874, 691, 18, 2878, 528, 751, 18, 1991, 30839, 31, 203, 3639, 309, 12, 2878, 528, 691, 18, 2293, 18, 2316, 8924, 480, 1758, 12, 20, 3719, 95, 203, 5411, 2583, 12, 2878, 528, 691, 18, 2293, 18, 2316, 6275, 1648, 467, 654, 39, 3462, 12, 2878, 528, 691, 2 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "../libs/IERC20.sol"; import "../libs/SafeERC20.sol"; import "../libs/FixedPoint.sol"; import "../libs/DaoOwnable.sol"; import "../libs/interface/ITreasury.sol"; import "../libs/interface/IBondCalculator.sol"; import "../libs/interface/IsGaas.sol"; import "../libs/interface/IStaking.sol"; import "../libs/SafeMath.sol"; contract CongruentBondStakeDepository is DaoOwnable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable Gaas; // reward token from treasury address public immutable sGaas; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints Gaas when receives principle address public immutable DAO; // receives profit share from bond bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public immutable bondCalculator; // calculates value of LP tokens address public stakingHelper; // to stake and claim if no staking warmup Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principle value, 4 decimals. i.e. 1.5 = 1500 uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder with gons struct Bond { uint gonsPayout; // sGaas gons remaining to be paid uint GaasPayout; // Gaas amount at the moment of bond uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _Gaas, address _sGaas, address _principle, address _treasury, address _DAO, address _bondCalculator ) { require( _Gaas != address(0) ); Gaas = _Gaas; require( _sGaas != address(0) ); sGaas = _sGaas; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt ) external onlyManager() { require( terms.controlVariable == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyManager() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyManager() { adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice set contract for auto stake * @param _staking address */ function setStaking( address _staking, bool ) external onlyManager() { require( _staking != address(0) ); stakingHelper = _staking; } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor ) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOf( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 Gaas ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) Gaas */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( Gaas ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( Gaas ).approve( stakingHelper, payout ); IStaking( stakingHelper ).stake( payout, address(this) ); uint stakeGons = IsGaas( sGaas ).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), GaasPayout: bondInfo[ _depositor ].GaasPayout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @return uint */ function redeem( address _recipient, bool ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) IStaking(stakingHelper).claim(address(this)); uint256 pendingGons; uint256 lockedGons; uint256 _amount; if ( percentVested >= 10000 ) { // if fully vested pendingGons = info.gonsPayout; delete bondInfo[ _recipient ]; // delete user info } else { // if unfinished // calculate payout vested pendingGons = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( pendingGons ), GaasPayout: info.GaasPayout, vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, pricePaid: info.pricePaid }); lockedGons = bondInfo[ _recipient ].gonsPayout; } _amount = IsGaas( sGaas ).balanceForGons(pendingGons); IERC20(sGaas).transfer( _recipient, _amount); emit BondRedeemed( _recipient, _amount, lockedGons ); // emit bond data return _amount; } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( Gaas ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e4 ); } else { price_ = bondPrice().mul( 10 ** IERC20( principle ).decimals() ).div( 1e4 ); } } /** * @notice calculate current ratio of debt to Gaas supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( Gaas ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of Gaas available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].gonsPayout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or Gaas) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != Gaas ); require( _token != sGaas ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the decimals of token. */ function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./ERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; library SafeERC20 { 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)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { 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) + 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) - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./FullMath.sol"; library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= type(uint144).max) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= type(uint224).max, 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= type(uint224).max, 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; contract DaoOwnable{ address internal _owner; address internal _newOwner; event OwnershipPushed(address indexed previousOwner, address indexed newOwner); event OwnershipPulled(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipPushed( address(0), _owner ); } function manager() public view returns (address) { return _owner; } modifier onlyManager() { require( _owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceManagement() public onlyManager() { emit OwnershipPushed( _owner, address(0) ); _owner = address(0); } function pushManagement( address newOwner_ ) public onlyManager() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipPushed( _owner, newOwner_ ); _newOwner = newOwner_; } function pullManagement() public { require( msg.sender == _newOwner, "Ownable: must be new owner to pull"); emit OwnershipPulled( _owner, _newOwner ); _owner = _newOwner; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function mintRewards( address _recipient, uint _amount ) external; function deposit( uint _amount, address _token, uint _profit ) external returns ( bool ); function valueOf( address _token, uint _amount ) external view returns ( uint value_ ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IBondCalculator { function valuation( address _LP, uint _amount ) external view returns ( uint ); function markdown( address _LP ) external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IsGaas { function rebase( uint256 METAProfit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); function INDEX() external view returns ( uint ); function totalSupply() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake( uint _amount, address _recipient ) external returns ( bool ); function claim( address _recipient ) external; function unstake( uint _amount, bool _trigger ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.6.0 <0.8.0; /** * @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; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } /* * Expects percentage to be trailed by 00, */ function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) { return div( mul( total_, percentage_ ), 1000 ); } /* * Expects percentage to be trailed by 00, */ function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) { return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) ); } function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) { return div( mul(part_, 100) , total_ ); } /** * Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) { return sqrrt( mul( multiplier_, payment_ ) ); } function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) { return mul( multiplier_, supply_ ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IERC20.sol"; import "./Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address, address, uint256) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } }
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
124,458
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 203, 202, 915, 15105, 1435, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 202, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x55486Dd002430bD8c739ce39A8CC7DdDf42c0409/sources/contracts/tes.sol
GET ALL PIG OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH Return an empty array
function pigNamesOfOwner(address _owner) external view returns(string[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new string[](0); string[] memory result = new string[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = pigNames[ tokenOfOwnerByIndex(_owner, index) ] ; } return result; } }
4,965,196
[ 1, 3264, 8061, 453, 3047, 15932, 432, 30293, 15146, 5355, 8175, 14884, 15932, 9469, 55, 18, 678, 31090, 9722, 9722, 11976, 490, 5255, 5948, 11083, 24142, 14780, 2056, 432, 7128, 9749, 13601, 1599, 17, 1985, 16585, 2000, 392, 1008, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 293, 360, 1557, 951, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 1135, 12, 1080, 8526, 3778, 262, 288, 203, 3639, 2254, 5034, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 327, 394, 533, 8526, 12, 20, 1769, 203, 5411, 533, 8526, 3778, 563, 273, 394, 533, 8526, 12, 2316, 1380, 1769, 203, 5411, 2254, 5034, 770, 31, 203, 5411, 364, 261, 1615, 273, 374, 31, 770, 411, 1147, 1380, 31, 770, 27245, 288, 203, 7734, 563, 63, 1615, 65, 273, 293, 360, 1557, 63, 1147, 951, 5541, 21268, 24899, 8443, 16, 770, 13, 308, 274, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//"SPDX-License-Identifier: UNLICENSED" /** *Submitted for verification at Etherscan.io on 2021-03-01 */ //"SPDX-License-Identifier: UNLICENSED" pragma solidity ^0.6.6; 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; } } 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); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface UniswapV2Router{ function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap(address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } contract Owned { //address of contract owner address public owner; //event for transfer of ownership event OwnershipTransferred(address indexed _from, address indexed _to); /** * @dev Initializes the contract setting the _owner as the initial owner. */ constructor(address _owner) public { owner = _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner, 'only owner allowed'); _; } /** * @dev Transfers ownership of the contract to a new account (`_newOwner`). * Can only be called by the current owner. */ function transferOwnership(address _newOwner) external onlyOwner { owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } } interface Multiplier { function updateLockupPeriod(address _user, uint _lockup) external returns(bool); function getMultiplierCeiling() external pure returns (uint); function balance(address user) external view returns (uint); function approvedContract(address _user) external view returns(address); function lockupPeriod(address user) external view returns (uint); } /* * @dev PoolStakes contract for locking up liquidity to earn bonus rewards. */ contract PoolStake is Owned { //instantiate SafeMath library using SafeMath for uint; IERC20 internal weth; //represents weth. IERC20 internal token; //represents the project's token which should have a weth pair on uniswap IERC20 internal lpToken; //lpToken for liquidity provisioning address internal uToken; //utility token address internal wallet; //company wallet uint internal scalar = 10**36; //unit for scaling uint internal cap; //ETH limit that can be provided Multiplier internal multiplier; //Interface of Multiplier contract UniswapV2Router internal uniswapRouter; //Interface of Uniswap V2 router IUniswapV2Factory internal iUniswapV2Factory; //Interface of uniswap V2 factory //user struct struct User { uint start; //starting period uint release; //release period uint tokenBonus; //user token bonus uint wethBonus; //user weth bonus uint tokenWithdrawn; //amount of token bonus withdrawn uint wethWithdrawn; //amount of weth bonus withdrawn uint liquidity; //user liquidity gotten from uniswap bool migrated; //if migrated to uniswap V3 } //address to User mapping mapping(address => User) internal _users; uint32 internal constant _012_HOURS_IN_SECONDS = 43200; //term periods uint32 internal period1; uint32 internal period2; uint32 internal period3; uint32 internal period4; //return percentages for ETH and token 1000 = 1% uint internal period1RPWeth; uint internal period2RPWeth; uint internal period3RPWeth; uint internal period4RPWeth; uint internal period1RPToken; uint internal period2RPToken; uint internal period3RPToken; uint internal period4RPToken; //available bonuses rto be claimed uint internal _pendingBonusesWeth; uint internal _pendingBonusesToken; //migration contract for Uniswap V3 address public migrationContract; //events event BonusAdded(address indexed sender, uint ethAmount, uint tokenAmount); event BonusRemoved(address indexed sender, uint amount); event CapUpdated(address indexed sender, uint amount); event LPWithdrawn(address indexed sender, uint amount); event LiquidityAdded(address indexed sender, uint liquidity, uint amountETH, uint amountToken); event LiquidityWithdrawn(address indexed sender, uint liquidity, uint amountETH, uint amountToken); event UserTokenBonusWithdrawn(address indexed sender, uint amount, uint fee); event UserETHBonusWithdrawn(address indexed sender, uint amount, uint fee); event VersionMigrated(address indexed sender, uint256 time, address to); event LiquidityMigrated(address indexed sender, uint amount, address to); /* * @dev initiates a new PoolStake. * ------------------------------------------------------ * @param _token --> token offered for staking liquidity. * @param _Owner --> address for the initial contract owner. */ constructor(address _token, address _Owner) public Owned(_Owner) { require(_token != address(0), "can not deploy a zero address"); token = IERC20(_token); weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); iUniswapV2Factory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); address _lpToken = iUniswapV2Factory.getPair(address(token), address(weth)); require(_lpToken != address(0), "Pair must first be created on uniswap"); lpToken = IERC20(_lpToken); uToken = 0x9Ed8e7C9604790F7Ec589F99b94361d8AAB64E5E; wallet = 0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a; multiplier = Multiplier(0xbc962d7be33d8AfB4a547936D8CE6b9a1034E9EE); uniswapRouter = UniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } /* * @dev change the return percentage for locking up liquidity for ETH and Token (only Owner). * ------------------------------------------------------------------------------------ * @param _period1RPETH - _period4RPToken --> the new return percentages. * ---------------------------------------------- * returns whether successfully changed or not. */ function changeReturnPercentages( uint _period1RPETH, uint _period2RPETH, uint _period3RPETH, uint _period4RPETH, uint _period1RPToken, uint _period2RPToken, uint _period3RPToken, uint _period4RPToken ) external onlyOwner returns(bool) { period1RPWeth = _period1RPETH; period2RPWeth = _period2RPETH; period3RPWeth = _period3RPETH; period4RPWeth = _period4RPETH; period1RPToken = _period1RPToken; period2RPToken = _period2RPToken; period3RPToken = _period3RPToken; period4RPToken = _period4RPToken; return true; } /* * @dev change the lockup periods (only Owner). * ------------------------------------------------------------------------------------ * @param _firstTerm - _fourthTerm --> the new term periods. * ---------------------------------------------- * returns whether successfully changed or not. */ function changeTermPeriods( uint32 _firstTerm, uint32 _secondTerm, uint32 _thirdTerm, uint32 _fourthTerm ) external onlyOwner returns(bool) { period1 = _firstTerm; period2 = _secondTerm; period3 = _thirdTerm; period4 = _fourthTerm; return true; } /* * @dev change the maximum ETH that a user can enter with (only Owner). * ------------------------------------------------------------------------------------ * @param _cap --> the new cap value. * ---------------------------------------------- * returns whether successfully changed or not. */ function changeCap(uint _cap) external onlyOwner returns(bool) { cap = _cap; emit CapUpdated(msg.sender, _cap); return true; } /* * @dev makes migration possible for uniswap V3 (only Owner). * ---------------------------------------------------------- * @param _unistakeMigrationContract --> the migration contract address. * ------------------------------------------------------------------------- * returns whether successfully migrated or not. */ function allowMigration(address _unistakeMigrationContract) external onlyOwner returns (bool) { require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address"); migrationContract = _unistakeMigrationContract; emit VersionMigrated(msg.sender, now, migrationContract); return true; } /* * @dev initiates migration for a user (only when migration is allowed). * ------------------------------------------------------------------- * @param _unistakeMigrationContract --> the migration contract address. * ------------------------------------------------------------------------- * returns whether successfully migrated or not. */ function startMigration(address _unistakeMigrationContract) external returns (bool) { require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address"); require(migrationContract == _unistakeMigrationContract, "must confirm endpoint"); require(!getUserMigration(msg.sender), "must not be migrated already"); _users[msg.sender].migrated = true; uint256 liquidity = _users[msg.sender].liquidity; lpToken.transfer(migrationContract, liquidity); emit LiquidityMigrated(msg.sender, liquidity, migrationContract); return true; } /* * @dev add more staking bonuses to the pool. * ---------------------------------------- * @param --> input value along with call to add ETH * @param _tokenAmount --> the amount of token to be added. * -------------------------------------------------------- * returns whether successfully added or not. */ function addBonus(uint _tokenAmount) external payable returns(bool) { require(_tokenAmount > 0 || msg.value > 0, "must send value"); if (_tokenAmount > 0) require(token.transferFrom(msg.sender, address(this), _tokenAmount), "must approve smart contract"); emit BonusAdded(msg.sender, msg.value, _tokenAmount); return true; } /* * @dev remove staking bonuses to the pool. (only owner) * must have enough asset to be removed * ---------------------------------------- * @param _amountETH --> eth amount to be removed * @param _amountToken --> token amount to be removed. * -------------------------------------------------------- * returns whether successfully added or not. */ function removeETHAndTokenBouses(uint _amountETH, uint _amountToken) external onlyOwner returns (bool success) { require(_amountETH > 0 || _amountToken > 0, "amount must be larger than zero"); if (_amountETH > 0) { require(_checkForSufficientStakingBonusesForETH(_amountETH), 'cannot withdraw above current ETH bonus balance'); msg.sender.transfer(_amountETH); emit BonusRemoved(msg.sender, _amountETH); } if (_amountToken > 0) { require(_checkForSufficientStakingBonusesForToken(_amountToken), 'cannot withdraw above current token bonus balance'); require(token.transfer(msg.sender, _amountToken), "error: token transfer failed"); emit BonusRemoved(msg.sender, _amountToken); } return true; } /* * @dev add unwrapped liquidity to staking pool. * -------------------------------------------- * @param _tokenAmount --> must input token amount along with call * @param _term --> the lockup term. * @param _multiplier --> whether multiplier should be used or not * 1 means you want to use the multiplier. !1 means no multiplier * -------------------------------------------------------------- * returns whether successfully added or not. */ function addLiquidity(uint _term, uint _multiplier) external payable returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); require(now >= _users[msg.sender].release, "cannot override current term"); require(_isValidTerm(_term), "must select a valid term"); require(msg.value > 0, "must send ETH along with transaction"); if (cap != 0) require(msg.value <= cap, "cannot provide more than the cap"); uint rate = _proportion(msg.value, address(weth), address(token)); require(token.transferFrom(msg.sender, address(this), rate), "must approve smart contract"); (uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender); require(ETH_bonus == 0 && token_bonus == 0, "must first withdraw available bonus"); uint oneTenthOfRate = (rate.mul(10)).div(100); token.approve(address(uniswapRouter), rate); (uint amountToken, uint amountETH, uint liquidity) = uniswapRouter.addLiquidityETH{value: msg.value}( address(token), rate.add(oneTenthOfRate), 0, 0, address(this), now.add(_012_HOURS_IN_SECONDS)); _users[msg.sender].start = now; _users[msg.sender].release = now.add(_term); uint previousLiquidity = _users[msg.sender].liquidity; _users[msg.sender].liquidity = previousLiquidity.add(liquidity); uint wethRP = _calculateReturnPercentage(weth, _term); uint tokenRP = _calculateReturnPercentage(token, _term); (uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender); if (_multiplier == 1) _withMultiplier(_term, provided_ETH, provided_token, wethRP, tokenRP); else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP); emit LiquidityAdded(msg.sender, liquidity, amountETH, amountToken); return true; } /* * @dev uses the Multiplier contract for double rewarding * ------------------------------------------------------ * @param _term --> the lockup term. * @param amountETH --> ETH amount provided in liquidity * @param amountToken --> token amount provided in liquidity * @param wethRP --> return percentge for ETH based on term period * @param tokenRP --> return percentge for token based on term period * -------------------------------------------------------------------- */ function _withMultiplier( uint _term, uint amountETH, uint amountToken, uint wethRP, uint tokenRP ) internal { require(multiplier.balance(msg.sender) > 0, "No Multiplier balance to use"); if (_term > multiplier.lockupPeriod(msg.sender)) multiplier.updateLockupPeriod(msg.sender, _term); uint multipliedETH = _proportion(multiplier.balance(msg.sender), uToken, address(weth)); uint multipliedToken = _proportion(multipliedETH, address(weth), address(token)); uint addedBonusWeth; uint addedBonusToken; if (_offersBonus(weth) && _offersBonus(token)) { if (multipliedETH > amountETH) { multipliedETH = (_calculateBonus((amountETH.mul(multiplier.getMultiplierCeiling())), wethRP)); addedBonusWeth = multipliedETH; } else { addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP)); } if (multipliedToken > amountToken) { multipliedToken = (_calculateBonus((amountToken.mul(multiplier.getMultiplierCeiling())), tokenRP)); addedBonusToken = multipliedToken; } else { addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP)); } require(_checkForSufficientStakingBonusesForETH(addedBonusWeth) && _checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } else if (_offersBonus(weth) && !_offersBonus(token)) { if (multipliedETH > amountETH) { multipliedETH = (_calculateBonus((amountETH.mul(multiplier.getMultiplierCeiling())), wethRP)); addedBonusWeth = multipliedETH; } else { addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP)); } require(_checkForSufficientStakingBonusesForETH(addedBonusWeth), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); } else if (!_offersBonus(weth) && _offersBonus(token)) { if (multipliedToken > amountToken) { multipliedToken = (_calculateBonus((amountToken.mul(multiplier.getMultiplierCeiling())), tokenRP)); addedBonusToken = multipliedToken; } else { addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP)); } require(_checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } } /* * @dev distributes bonus without considering Multiplier * ------------------------------------------------------ * @param amountETH --> ETH amount provided in liquidity * @param amountToken --> token amount provided in liquidity * @param wethRP --> return percentge for ETH based on term period * @param tokenRP --> return percentge for token based on term period * -------------------------------------------------------------------- */ function _withoutMultiplier( uint amountETH, uint amountToken, uint wethRP, uint tokenRP ) internal { uint addedBonusWeth; uint addedBonusToken; if (_offersBonus(weth) && _offersBonus(token)) { addedBonusWeth = _calculateBonus(amountETH, wethRP); addedBonusToken = _calculateBonus(amountToken, tokenRP); require(_checkForSufficientStakingBonusesForETH(addedBonusWeth) && _checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } else if (_offersBonus(weth) && !_offersBonus(token)) { addedBonusWeth = _calculateBonus(amountETH, wethRP); require(_checkForSufficientStakingBonusesForETH(addedBonusWeth), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); } else if (!_offersBonus(weth) && _offersBonus(token)) { addedBonusToken = _calculateBonus(amountToken, tokenRP); require(_checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } } /* * @dev relocks liquidity already provided * -------------------------------------------- * @param _term --> the lockup term. * @param _multiplier --> whether multiplier should be used or not * 1 means you want to use the multiplier. !1 means no multiplier * -------------------------------------------------------------- * returns whether successfully relocked or not. */ function relockLiquidity(uint _term, uint _multiplier) external returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); require(_users[msg.sender].liquidity > 0, "do not have any liquidity to lock"); require(now >= _users[msg.sender].release, "cannot override current term"); require(_isValidTerm(_term), "must select a valid term"); (uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender); require (ETH_bonus == 0 && token_bonus == 0, 'must withdraw available bonuses first'); (uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender); if (cap != 0) require(provided_ETH <= cap, "cannot provide more than the cap"); uint wethRP = _calculateReturnPercentage(weth, _term); uint tokenRP = _calculateReturnPercentage(token, _term); _users[msg.sender].start = now; _users[msg.sender].release = now.add(_term); if (_multiplier == 1) _withMultiplier(_term, provided_ETH, provided_token, wethRP, tokenRP); else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP); return true; } /* * @dev withdraw unwrapped liquidity by user if released. * ------------------------------------------------------- * @param _lpAmount --> takes the amount of user's lp token to be withdrawn. * ------------------------------------------------------------------------- * returns whether successfully withdrawn or not. */ function withdrawLiquidity(uint _lpAmount) external returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); uint liquidity = _users[msg.sender].liquidity; require(_lpAmount > 0 && _lpAmount <= liquidity, "do not have any liquidity"); require(now >= _users[msg.sender].release, "cannot override current term"); _users[msg.sender].liquidity = liquidity.sub(_lpAmount); lpToken.approve(address(uniswapRouter), _lpAmount); (uint amountToken, uint amountETH) = uniswapRouter.removeLiquidityETH( address(token), _lpAmount, 1, 1, msg.sender, now.add(_012_HOURS_IN_SECONDS)); emit LiquidityWithdrawn(msg.sender, _lpAmount, amountETH, amountToken); return true; } /* * @dev withdraw LP token by user if released. * ------------------------------------------------------- * returns whether successfully withdrawn or not. */ function withdrawUserLP() external returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); uint liquidity = _users[msg.sender].liquidity; require(liquidity > 0, "do not have any liquidity"); require(now >= _users[msg.sender].release, "cannot override current term"); _users[msg.sender].liquidity = 0; lpToken.transfer(msg.sender, liquidity); emit LPWithdrawn(msg.sender, liquidity); return true; } /* * @dev withdraw available staking bonuses earned from locking up liquidity. * -------------------------------------------------------------- * returns whether successfully withdrawn or not. */ function withdrawUserBonus() public returns(bool) { (uint ETH_bonus, uint token_bonus) = getUserBonusAvailable(msg.sender); require(ETH_bonus > 0 || token_bonus > 0, "you do not have any bonus available"); uint releasedToken = _calculateTokenReleasedAmount(msg.sender); uint releasedETH = _calculateETHReleasedAmount(msg.sender); if (releasedToken > 0 && releasedETH > 0) { _withdrawUserTokenBonus(msg.sender, releasedToken); _withdrawUserETHBonus(msg.sender, releasedETH); } else if (releasedETH > 0 && releasedToken == 0) _withdrawUserETHBonus(msg.sender, releasedETH); else if (releasedETH == 0 && releasedToken > 0) _withdrawUserTokenBonus(msg.sender, releasedToken); if (_users[msg.sender].release <= now) { _users[msg.sender].wethWithdrawn = 0; _users[msg.sender].tokenWithdrawn = 0; _users[msg.sender].wethBonus = 0; _users[msg.sender].tokenBonus = 0; } return true; } /* * @dev withdraw ETH bonus earned from locking up liquidity * -------------------------------------------------------------- * @param _user --> address of the user making withdrawal * @param releasedAmount --> released ETH to be withdrawn * ------------------------------------------------------------------ * returns whether successfully withdrawn or not. */ function _withdrawUserETHBonus(address payable _user, uint releasedAmount) internal returns(bool) { _users[_user].wethWithdrawn = _users[_user].wethWithdrawn.add(releasedAmount); _pendingBonusesWeth = _pendingBonusesWeth.sub(releasedAmount); (uint fee, uint feeInETH) = _calculateETHFee(releasedAmount); require(IERC20(uToken).transferFrom(_user, wallet, fee), "must approve fee"); _user.transfer(releasedAmount); emit UserETHBonusWithdrawn(_user, releasedAmount, feeInETH); return true; } /* * @dev withdraw token bonus earned from locking up liquidity * -------------------------------------------------------------- * @param _user --> address of the user making withdrawal * @param releasedAmount --> released token to be withdrawn * ------------------------------------------------------------------ * returns whether successfully withdrawn or not. */ function _withdrawUserTokenBonus(address _user, uint releasedAmount) internal returns(bool) { _users[_user].tokenWithdrawn = _users[_user].tokenWithdrawn.add(releasedAmount); _pendingBonusesToken = _pendingBonusesToken.sub(releasedAmount); (uint fee, uint feeInToken) = _calculateTokenFee(releasedAmount); require(IERC20(uToken).transferFrom(_user, wallet, fee), "must approve fee"); token.transfer(_user, releasedAmount); emit UserTokenBonusWithdrawn(_user, releasedAmount, feeInToken); return true; } /* * @dev gets an asset's amount in proportion of a pair asset * --------------------------------------------------------- * param _amount --> the amount of first asset * param _tokenA --> the address of the first asset * param _tokenB --> the address of the second asset * ------------------------------------------------- * returns the propotion of the _tokenB */ function _proportion(uint _amount, address _tokenA, address _tokenB) internal view returns(uint tokenBAmount) { (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(address(iUniswapV2Factory), _tokenA, _tokenB); return UniswapV2Library.quote(_amount, reserveA, reserveB); } /* * @dev gets the released Token value * -------------------------------- * param _user --> the address of the user * ------------------------------------------------------ * returns the released amount in Token */ function _calculateTokenReleasedAmount(address _user) internal view returns(uint) { uint release = _users[_user].release; uint start = _users[_user].start; uint taken = _users[_user].tokenWithdrawn; uint tokenBonus = _users[_user].tokenBonus; uint releasedPct; if (now >= release) releasedPct = 100; else releasedPct = ((now.sub(start)).mul(100000)).div((release.sub(start)).mul(1000)); uint released = (((tokenBonus).mul(releasedPct)).div(100)); return released.sub(taken); } /* * @dev gets the released ETH value * -------------------------------- * param _user --> the address of the user * ------------------------------------------------------ * returns the released amount in ETH */ function _calculateETHReleasedAmount(address _user) internal view returns(uint) { uint release = _users[_user].release; uint start = _users[_user].start; uint taken = _users[_user].wethWithdrawn; uint wethBonus = _users[_user].wethBonus; uint releasedPct; if (now >= release) releasedPct = 100; else releasedPct = ((now.sub(start)).mul(10000)).div((release.sub(start)).mul(100)); uint released = (((wethBonus).mul(releasedPct)).div(100)); return released.sub(taken); } /* * @dev get the required fee for the released token bonus in the utility token * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount in the utility token and Token */ function _calculateTokenFee(uint _amount) internal view returns(uint uTokenFee, uint tokenFee) { uint fee = (_amount.mul(10)).div(100); uint feeInETH = _proportion(fee, address(token), address(weth)); uint feeInUtoken = _proportion(feeInETH, address(weth), address(uToken)); return (feeInUtoken, fee); } /* * @dev get the required fee for the released ETH bonus in the utility token * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount in the utility token and ETH */ function _calculateETHFee(uint _amount) internal view returns(uint uTokenFee, uint ethFee) { uint fee = (_amount.mul(10)).div(100); uint feeInUtoken = _proportion(fee, address(weth), address(uToken)); return (feeInUtoken, fee); } /* * @dev get the required fee for the released ETH bonus * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount. */ function calculateETHBonusFee(address _user) external view returns(uint ETH_Fee) { uint wethReleased = _calculateETHReleasedAmount(_user); if (wethReleased > 0) { (uint feeForWethInUtoken,) = _calculateETHFee(wethReleased); return feeForWethInUtoken; } else return 0; } /* * @dev get the required fee for the released token bonus * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount. */ function calculateTokenBonusFee(address _user) external view returns(uint token_Fee) { uint tokenReleased = _calculateTokenReleasedAmount(_user); if (tokenReleased > 0) { (uint feeForTokenInUtoken,) = _calculateTokenFee(tokenReleased); return feeForTokenInUtoken; } else return 0; } /* * @dev get the bonus based on the return percentage for a particular locking term. * ------------------------------------------------------------------------------- * param _amount --> the amount to calculate bonus from. * param _returnPercentage --> the returnPercentage of the term. * ---------------------------------------------------------- * returns the bonus amount. */ function _calculateBonus(uint _amount, uint _returnPercentage) internal pure returns(uint) { return ((_amount.mul(_returnPercentage)).div(100000)) / 2; // 1% = 1000 } /* * @dev get the correct return percentage based on locked term. * ----------------------------------------------------------- * @param _token --> associated asset. * @param _term --> the locking term. * ---------------------------------------------------------- * returns the return percentage. */ function _calculateReturnPercentage(IERC20 _token, uint _term) internal view returns(uint) { if (_token == weth) { if (_term == period1) return period1RPWeth; else if (_term == period2) return period2RPWeth; else if (_term == period3) return period3RPWeth; else if (_term == period4) return period4RPWeth; else return 0; } else if (_token == token) { if (_term == period1) return period1RPToken; else if (_term == period2) return period2RPToken; else if (_term == period3) return period3RPToken; else if (_term == period4) return period4RPToken; else return 0; } } /* * @dev check whether the input locking term is one of the supported terms. * ---------------------------------------------------------------------- * @param _term --> the locking term. * ------------------------------- * returns whether true or not. */ function _isValidTerm(uint _term) internal view returns(bool) { if (_term == period1 || _term == period2 || _term == period3 || _term == period4) return true; else return false; } /* * @dev get the amount ETH and Token liquidity provided by the user. * ------------------------------------------------------------------ * @param _user --> the address of the user. * --------------------------------------- * returns the amount of ETH and Token liquidity provided. */ function getUserLiquidity(address _user) public view returns(uint provided_ETH, uint provided_token) { uint total = lpToken.totalSupply(); uint ratio = ((_users[_user].liquidity).mul(scalar)).div(total); uint tokenHeld = token.balanceOf(address(lpToken)); uint wethHeld = weth.balanceOf(address(lpToken)); return ((ratio.mul(wethHeld)).div(scalar), (ratio.mul(tokenHeld)).div(scalar)); } /* * @dev check whether the inputted user address has been migrated. * ---------------------------------------------------------------------- * @param _user --> ddress of the user * --------------------------------------- * returns whether true or not. */ function getUserMigration(address _user) public view returns (bool) { return _users[_user].migrated; } /* * @dev check whether the inputted user token has currently offers bonus * ---------------------------------------------------------------------- * @param _token --> associated token * --------------------------------------- * returns whether true or not. */ function _offersBonus(IERC20 _token) internal view returns (bool) { if (_token == weth) { uint wethRPTotal = period1RPWeth.add(period2RPWeth).add(period3RPWeth).add(period4RPWeth); if (wethRPTotal > 0) return true; else return false; } else if (_token == token) { uint tokenRPTotal = period1RPToken.add(period2RPToken).add(period3RPToken).add(period4RPToken); if (tokenRPTotal > 0) return true; else return false; } } /* * @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes. * ---------------------------------------------------------------------------------------------- * @param amount --> the _amount to be evaluated against. * --------------------------------------------------- * returns whether true or not. */ function _checkForSufficientStakingBonusesForETH(uint _amount) internal view returns(bool) { if ((address(this).balance).sub(_pendingBonusesWeth) >= _amount) { return true; } else { return false; } } /* * @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes. * ---------------------------------------------------------------------------------------------- * @param amount --> the _amount to be evaluated against. * --------------------------------------------------- * returns whether true or not. */ function _checkForSufficientStakingBonusesForToken(uint _amount) internal view returns(bool) { if ((token.balanceOf(address(this)).sub(_pendingBonusesToken)) >= _amount) { return true; } else { return false; } } /* * @dev get the timestamp of when the user balance will be released from locked term. * --------------------------------------------------------------------------------- * @param _user --> the address of the user. * --------------------------------------- * returns the timestamp for the release. */ function getUserRelease(address _user) external view returns(uint release_time) { uint release = _users[_user].release; if (release > now) { return (release.sub(now)); } else { return 0; } } /* * @dev get the amount of bonuses rewarded from staking to a user. * -------------------------------------------------------------- * @param _user --> the address of the user. * --------------------------------------- * returns the amount of staking bonuses. */ function getUserBonusPending(address _user) public view returns(uint ETH_bonus, uint token_bonus) { uint takenWeth = _users[_user].wethWithdrawn; uint takenToken = _users[_user].tokenWithdrawn; return (_users[_user].wethBonus.sub(takenWeth), _users[_user].tokenBonus.sub(takenToken)); } /* * @dev get the amount of released bonuses rewarded from staking to a user. * -------------------------------------------------------------- * @param _user --> the address of the user. * --------------------------------------- * returns the amount of released staking bonuses. */ function getUserBonusAvailable(address _user) public view returns(uint ETH_Released, uint token_Released) { uint ETHValue = _calculateETHReleasedAmount(_user); uint tokenValue = _calculateTokenReleasedAmount(_user); return (ETHValue, tokenValue); } /* * @dev get the amount of liquidity pool tokens staked/locked by user. * ------------------------------------------------------------------ * @param _user --> the address of the user. * --------------------------------------- * returns the amount of locked liquidity. */ function getUserLPTokens(address _user) external view returns(uint user_LP) { return _users[_user].liquidity; } /* * @dev get the lp token address for the pair. * ----------------------------------------------------------- * returns the lp address for eth/token pair. */ function getLPAddress() external view returns(address) { return address(lpToken); } /* * @dev get the amount of staking bonuses available in the pool. * ----------------------------------------------------------- * returns the amount of staking bounses available for ETH and Token. */ function getAvailableBonus() external view returns(uint available_ETH, uint available_token) { available_ETH = (address(this).balance).sub(_pendingBonusesWeth); available_token = (token.balanceOf(address(this))).sub(_pendingBonusesToken); return (available_ETH, available_token); } /* * @dev get the maximum amount of ETH allowed for provisioning. * ----------------------------------------------------------- * returns the maximum ETH allowed */ function getCap() external view returns(uint maxETH) { return cap; } /* * @dev checks the term period and return percentages * -------------------------------------------------- * returns term period and return percentages */ function getTermPeriodAndReturnPercentages() external view returns( uint Term_Period_1, uint Term_Period_2, uint Term_Period_3, uint Term_Period_4, uint Period_1_Return_Percentage_Token, uint Period_2_Return_Percentage_Token, uint Period_3_Return_Percentage_Token, uint Period_4_Return_Percentage_Token, uint Period_1_Return_Percentage_ETH, uint Period_2_Return_Percentage_ETH, uint Period_3_Return_Percentage_ETH, uint Period_4_Return_Percentage_ETH ) { return ( period1, period2, period3, period4, period1RPToken, period2RPToken, period3RPToken, period4RPToken,period1RPWeth, period2RPWeth, period3RPWeth, period4RPWeth); } } contract PoolStakeFactory { //array of PoolStake contracts address[] private _poolStakes; //event on contract creation event Created(address indexed Creator, address Contract, address indexed Token); /* * @dev get the length of all contracts created * ----------------------------------------------------------- * returns number of contracts created */ function totalContracts() external view returns(uint256) { return _poolStakes.length; } /* * @dev get an array of all contracts created * ----------------------------------------------------------- * returns all contracts created */ function getContracts() external view returns(address[] memory) { return _poolStakes; } /* * @dev create a new contract prototype. * ------------------------------------- * @param _token --> the ETH-pair token address * ------------------------------------------------- * returns whether successfully changed or not. */ function createContract(address _token) external returns(bool) { PoolStake poolStake = new PoolStake(_token, msg.sender); _poolStakes.push(address(poolStake)); emit Created(msg.sender, address(poolStake), _token); return true; } }
Interface of Uniswap V2 router
UniswapV2Router internal uniswapRouter;
577,554
[ 1, 1358, 434, 1351, 291, 91, 438, 776, 22, 4633, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1351, 291, 91, 438, 58, 22, 8259, 2713, 640, 291, 91, 438, 8259, 31, 5375, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x1834D034868c27F9d61C42994aFD349527A9c98E/sources/contracts/ccl.sol
WE need to check if the public address is verified or not
mapping (address => bool) public isVerified;
3,290,145
[ 1, 6950, 1608, 358, 866, 309, 326, 1071, 1758, 353, 13808, 578, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 24369, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** @title Proof Storage */ contract ProofStorage { /** @dev Owner being the platform admin */ address public owner; /** @dev Locking bool */ bool public lock; /** @dev Every proof can have the following states: Empty, Generated, Acknowledged, Verified, Discarded */ enum State { Empty, Generated, Acknowledged, Verified, Discarded } /** @dev Logs a New proof */ event LogNewProof(string _proof, address _address, State _state, uint _timestamp); /** @dev Logs an Acknowledged proof */ event LogProofAcknowledged(string _proof, address _address, State _state, uint _timestamp); /** @dev Logs a Verified proof */ event LogProofVerified(string _proof, address _address, State _state, uint _timestamp); /** @dev Logs a Discarded proof */ event LogProofDiscarded(string _proof, address _address, State _state, uint _timestamp); /** @dev Logs a Payout proof */ event LogProofPayout(string _proof, address _address, State _state, uint _amount, uint _timestamp); /** @dev Logs a contract Locked state */ event LogLockTriggered(bool _lock); /** @dev Structure of a proof * @param created Creation date * @param stateChanged Updated date * @param state Current state * @param sender User address */ struct Proof { uint created; uint stateChanged; State state; address sender; } /** @dev Maps each proof structure to the actual Proof */ mapping(string => Proof) proofs; constructor() public { owner = msg.sender; } /** @dev Verifies if it is the owner */ modifier isOwner() { require(owner == msg.sender, "Sender address doesn't match owner"); _; } /** @dev Verifies if it is the owner or the creator of the Proof * @param _proof String representing the Proof */ modifier isCreaterOrOwner(string _proof) { require((proofs[_proof].sender == msg.sender) || (owner == msg.sender), "Sender address doesn't match owner or proof creator"); _; } /** @dev Verifies the locked state of the contract */ modifier isNotLocked() { require(!lock, "Contract is locked"); _; } /** @dev Verifies if Proof exists * @param _proof String representing the Proof */ modifier isProof(string _proof) { require(proofs[_proof].state != State.Empty, "Proof doesn't exist"); _; } /** @dev Verifies if Proof is in the Empty state * @param _proof String representing the Proof */ modifier isEmpty(string _proof) { require(proofs[_proof].state == State.Empty, "Proof needs to be on an Empty state"); _; } /** @dev Verifies if Proof is in the Genereated state * @param _proof String representing the Proof */ modifier isGenerated(string _proof) { require(proofs[_proof].state == State.Generated, "Proof needs to be on a Generated state"); _; } /** @dev Verifies if Proof is in the Aknowledged state * @param _proof String representing the Proof */ modifier isAknowledge(string _proof) { require(proofs[_proof].state == State.Acknowledged, "Proof needs to be on an Acknowledged state"); _; } /** @dev Triggers the locking/unlocking of the contract */ function triggerLock() public isOwner() { lock = !lock; emit LogLockTriggered(lock); } /** @dev Creates a new Proof * @param _proof String representing the Proof */ function provideProof(string _proof) public isNotLocked() isEmpty(_proof) { proofs[_proof] = Proof(block.timestamp, block.timestamp, State.Generated, msg.sender); emit LogNewProof(_proof, proofs[_proof].sender, proofs[_proof].state, proofs[_proof].stateChanged); } /** @dev Aknowledges a Proof * @param _proof String representing the Proof */ function aknowledgeProof(string _proof) public isNotLocked() isOwner() isGenerated(_proof) { proofs[_proof].state = State.Acknowledged; emit LogProofAcknowledged(_proof, proofs[_proof].sender, proofs[_proof].state, proofs[_proof].stateChanged); } /** @dev Verifies a Proof * @param _proof String representing the Proof */ function verifyProof(string _proof) public isNotLocked() isOwner() isAknowledge(_proof) { proofs[_proof].state = State.Verified; emit LogProofVerified(_proof, proofs[_proof].sender, proofs[_proof].state, proofs[_proof].stateChanged); // At this point, a token transfer should be triggered emit LogProofPayout(_proof, proofs[_proof].sender, proofs[_proof].state, 20, proofs[_proof].stateChanged); } /** @dev Discards a Proof * @param _proof String representing the Proof */ function discardProof(string _proof) public isNotLocked() isOwner() isAknowledge(_proof) { proofs[_proof].state = State.Discarded; emit LogProofDiscarded(_proof, proofs[_proof].sender, proofs[_proof].state, proofs[_proof].stateChanged); } /** @dev Gets a Proof * @param _proof String representing the Proof */ function getProof(string _proof) public view isProof(_proof) isCreaterOrOwner(_proof) returns( uint, uint, State, address ) { return ( proofs[_proof].created, proofs[_proof].stateChanged, proofs[_proof].state, proofs[_proof].sender ); } }
* @dev Owner being the platform admin/* @dev Locking bool/* @dev Every proof can have the following states: Empty, Generated, Acknowledged, Verified, Discarded/
enum State { Empty, Generated, Acknowledged, Verified, Discarded }
6,399,204
[ 1, 5541, 3832, 326, 4072, 3981, 19, 225, 3488, 310, 1426, 19, 225, 16420, 14601, 848, 1240, 326, 3751, 5493, 30, 8953, 16, 11025, 16, 22322, 10378, 2423, 16, 6160, 939, 16, 3035, 16500, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 3287, 288, 8953, 16, 11025, 16, 22322, 10378, 2423, 16, 6160, 939, 16, 3035, 16500, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.13; import "./interfaces/IERC721Full.sol"; import "./utils/SafeMath.sol"; /// @title Augur Markets interface /// @notice Gets the winner of each market from Augur interface IMarket { function getWinningPayoutNumerator(uint256 _outcome) external view returns (uint256); } /// @title Dai contract interface /// @notice Various cash functions interface Cash { function approve(address _spender, uint256 _amount) external returns (bool); function balanceOf(address _ownesr) external view returns (uint256); function faucet(uint256 _amount) external; function transfer(address _to, uint256 _amount) external returns (bool); function transferFrom(address _from, address _to, uint256 _amount) external returns (bool); } /// @title Augur OICash interface /// @notice adding or removing open interest to secure the Augur Oracle interface OICash { function deposit(uint256 _amount) external returns (bool); function withdraw(uint256 _amount) external returns (bool); } //TODO: replace completesets with OICash //TODO: update design pattens to take into account the recent changes //TODO: change front end to only approve the same amount that is being sent //TODO: add test where someone calls exit and they are not the current owner //TODO: add tests where current owner calls newRental twice // ^ will also need to figure out how to pass this number in the correct format because decimal // ^ does not seem to work for more than 100 dai, it needs big number /// @title Harber /// @author Andrew Stanger contract Harber { using SafeMath for uint256; /// NUMBER OF TOKENS /// @dev also equals number of markets on augur uint256 constant public numberOfTokens = 20; /// CONTRACT VARIABLES /// ERC721: IERC721Full public team; /// Augur contracts: IMarket[numberOfTokens] public market; OICash public augur; Cash public cash; /// UINTS, ADDRESSES, BOOLS /// @dev my whiskey fund, for my 1% cut address private andrewsAddress; /// @dev the addresses of the various Augur binary markets. One market for each token. Initiated in the constructor and does not change. address[numberOfTokens] public marketAddresses; /// @dev in attodai (so $100 = 100000000000000000000) uint256[numberOfTokens] public price; /// @dev an easy way to track the above across all tokens. It should always increment at the same time as the above increments. uint256 public totalCollected; /// @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now. uint256[numberOfTokens] public timeLastCollected; /// @dev when a token was bought. used only for front end 'owned since' section. Rent collection only needs timeLastCollected. uint256[numberOfTokens] public timeAcquired; /// @dev tracks the position of the current owner in the ownerTracker mapping uint256[numberOfTokens] public currentOwnerIndex; /// WINNING OUTCOME VARIABLES /// @dev start with invalid winning outcome uint256 public winningOutcome = 42069; //// @dev so the function to manually set the winner can only be called long after /// @dev ...it should have resolved via Augur. Must be public so others can verify it is accurate. uint256 public marketExpectedResolutionTime; /// MARKET RESOLUTION VARIABLES /// @dev step1: bool public marketsResolved = false; // must be false for step1, true for step2 bool public marketsResolvedWithoutErrors = false; // set in step 1. If true, normal payout. If false, return all funds /// @dev step 2: bool public step2Complete = false; // must be false for step2, true for complete /// @dev step 3: bool public step3Complete = false; // must be false for step2, true for complete /// @dev complete: uint256 public daiAvailableToDistribute; /// STRUCTS struct purchase { address owner; uint256 price; } /// MAPPINGS /// @dev keeps track of all previous owners of a token, including the price, so that if the current owner's deposit runs out, /// @dev ...ownership can be reverted to a previous owner with the previous price. Index 0 is NOT used, this tells the contract to foreclose. /// @dev this does NOT keep a reliable list of all owners, if it reverts to a previous owner then the next owner will overwrite the owner that was in that slot. /// @dev the variable currentOwnerIndex is used to track the location of the current owner. mapping (uint256 => mapping (uint256 => purchase) ) public ownerTracker; /// @dev how many seconds each user has held each token for, for determining winnings mapping (uint256 => mapping (address => uint256) ) public timeHeld; /// @dev sums all the timeHelds for each token. Not required, but saves on gas when paying out. Should always increment at the same time as timeHeld mapping (uint256 => uint256) public totalTimeHeld; /// @dev keeps track of all the deposits for each token, for each owner. Unused deposits are not returned automatically when there is a new buyer. /// @dev they can be withdrawn manually however. Unused deposits are returned automatically upon resolution of the market mapping (uint256 => mapping (address => uint256) ) public deposits; /// @dev keeps track of all the rent paid by each user. So that it can be returned in case of an invalid market outcome. Only required in this instance. mapping (address => uint256) public collectedPerUser; ////////////// CONSTRUCTOR ////////////// constructor(address _andrewsAddress, address _addressOfToken, address _addressOfCashContract, address[numberOfTokens] memory _addressesOfMarkets, address _addressOfOICashContract, address _addressOfMainAugurContract, uint _marketExpectedResolutionTime) public { marketExpectedResolutionTime = _marketExpectedResolutionTime; andrewsAddress = _andrewsAddress; marketAddresses = _addressesOfMarkets; // this is to make the market addresses public so users can check the actual augur markets for themselves // external contract variables: team = IERC721Full(_addressOfToken); cash = Cash(_addressOfCashContract); augur = OICash(_addressOfOICashContract); // initialise arrays for (uint i = 0; i < numberOfTokens; i++) { currentOwnerIndex[i]=0; market[i] = IMarket(_addressesOfMarkets[i]); } // approve Augur contract to transfer this contract's dai cash.approve(_addressOfMainAugurContract,(2**256)-1); } event LogNewRental(address indexed newOwner, uint256 indexed newPrice, uint256 indexed tokenId); event LogPriceChange(uint256 indexed newPrice, uint256 indexed tokenId); event LogForeclosure(address indexed prevOwner, uint256 indexed tokenId); event LogRentCollection(uint256 indexed rentCollected, uint256 indexed tokenId); event LogReturnToPreviousOwner(uint256 indexed tokenId, address indexed previousOwner); event LogDepositWithdrawal(uint256 indexed daiWithdrawn, uint256 indexed tokenId, address indexed returnedTo); event LogDepositIncreased(uint256 indexed daiDeposited, uint256 indexed tokenId, address indexed sentBy); event LogExit(uint256 indexed tokenId); event LogStep1Complete(bool indexed didAugurMarketsResolve, uint256 indexed winningOutcome, bool indexed didAugurMarketsResolveCorrectly); event LogStep2Complete(uint256 indexed daiAvailableToDistribute); event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid); event LogRentReturned(address indexed returnedTo, uint256 indexed amountReturned); event LogAndrewPaid(uint256 indexed additionsToWhiskeyFund); ////////////// MODIFIERS ////////////// /// @notice prevents functions from being interacted with after the end of the competition /// @dev should be on all public/external 'ordinary course of business' functions modifier notResolved() { require(marketsResolved == false); _; } /// @notice checks the team exists modifier tokenExists(uint256 _tokenId) { require(_tokenId >= 0 && _tokenId < numberOfTokens, "This token does not exist"); _; } /// @notice what it says on the tin modifier amountNotZero(uint256 _dai) { require(_dai > 0, "Amount must be above zero"); _; } ////////////// VIEW FUNCTIONS ////////////// /// @dev used in testing only function getOwnerTrackerPrice(uint256 _tokenId, uint256 _index) public view returns (uint256) { return (ownerTracker[_tokenId][_index].price); } /// @dev used in testing only function getOwnerTrackerAddress(uint256 _tokenId, uint256 _index) public view returns (address) { return (ownerTracker[_tokenId][_index].owner); } /// @dev called in collectRent function, and various other view functions function rentOwed(uint256 _tokenId) public view returns (uint256 augurFundsDue) { return price[_tokenId].mul(now.sub(timeLastCollected[_tokenId])).div(1 days); } /// @dev for front end only /// @return how much the current owner has deposited function liveDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_rentOwed >= deposits[_tokenId][_currentOwner]) { return 0; } else { return deposits[_tokenId][_currentOwner].sub(_rentOwed); } } /// @dev for front end only /// @return how much the current user has deposited (note: user not owner) function userDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender) { if(_rentOwed >= deposits[_tokenId][msg.sender]) { return 0; } else { return deposits[_tokenId][msg.sender].sub(_rentOwed); } } else { return deposits[_tokenId][msg.sender]; } } /// @dev for front end only /// @return estimated rental expiry time function rentalExpiryTime(uint256 _tokenId) public view returns (uint256) { uint256 pps; pps = price[_tokenId].div(1 days); if (pps == 0) { return now; //if price is so low that pps = 0 just return current time as a fallback } else { return now + liveDepositAbleToWithdraw(_tokenId).div(pps); } } ////////////// AUGUR FUNCTIONS ////////////// // * internal * /// @notice send the Dai to Augur function _augurDeposit(uint256 _rentOwed) internal { augur.deposit(_rentOwed); } // * internal * /// @notice receive the Dai back from Augur function _augurWithdraw() internal { augur.withdraw(totalCollected); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all X (x = number of tokens = number of teams) markets have resolved to either yes, no, or invalid /// @return true if yes, false if no function _haveAllAugurMarketsResolved() internal view returns(bool) { uint256 _resolvedOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { // binary market has three outcomes: 0 (invalid), 1 (yes), 2 (no) if (market[i].getWinningPayoutNumerator(0) > 0 || market[i].getWinningPayoutNumerator(1) > 0 || market[i].getWinningPayoutNumerator(2) > 0 ) { _resolvedOutcomesCount = _resolvedOutcomesCount.add(1); } } // returns true if all resolved, false otherwise return (_resolvedOutcomesCount == numberOfTokens); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all markets have resolved without conflicts or errors /// @return true if yes, false if no /// @dev this function will also set the winningOutcome variable function _haveAllAugurMarketsResolvedWithoutErrors() internal returns(bool) { uint256 _winningOutcomesCount = 0; uint256 _invalidOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { if (market[i].getWinningPayoutNumerator(0) > 0) { _invalidOutcomesCount = _invalidOutcomesCount.add(1); } if (market[i].getWinningPayoutNumerator(1) > 0) { winningOutcome = i; // <- the winning outcome (a global variable) is set here _winningOutcomesCount = _winningOutcomesCount.add(1); } } return (_winningOutcomesCount == 1 && _invalidOutcomesCount == 0); } ////////////// DAI CONTRACT FUNCTIONS ////////////// // * internal * /// @notice common function for all outgoing DAI transfers function _sendCash(address _to, uint256 _amount) internal { require(cash.transfer(_to,_amount)); } // * internal * /// @notice common function for all incoming DAI transfers function _receiveCash(address _from, uint256 _amount) internal { require(cash.transferFrom(_from, address(this), _amount)); } // * internal * /// @return DAI balance of the contract /// @dev this is used to know how much exists to payout to winners function _getContractsCashBalance() internal view returns (uint256) { return cash.balanceOf(address(this)); } ////////////// MARKET RESOLUTION FUNCTIONS ////////////// /// @notice the first of three functions which must be called, one after the other, to conclude the competition /// @notice winnings can be paid out (or funds returned) only when these two steps are completed /// @notice this function checks whether the Augur markets have resolved, and if yes, whether they resolved correct or not /// @dev they are split into two sections due to the presence of step1BemergencyExit and step1CcircuitBreaker /// @dev can be called by anyone /// @dev can be called multiple times, but only once after markets have indeed resolved /// @dev the two arguments passed are for testing only function step1checkMarketsResolved() external { require(marketsResolved == false, "Step1 can only be completed once"); // first check if all X markets have all resolved one way or the other if (_haveAllAugurMarketsResolved()) { // do a final rent collection before the contract is locked down collectRentAllTokens(); // lock everything down marketsResolved = true; // now check if they all resolved without errors. It is set to false upon contract initialisation // this function also sets winningOutcome if there is one if (_haveAllAugurMarketsResolvedWithoutErrors()) { marketsResolvedWithoutErrors = true; } emit LogStep1Complete(true, winningOutcome, marketsResolvedWithoutErrors); } } /// @notice emergency function in case the augur markets never resolve for whatever reason /// @notice returns all funds to all users /// @notice can only be called 6 months after augur markets should have ended function step1BemergencyExit() external { require(marketsResolved == false, "Step1 can only be completed once"); require(now > (marketExpectedResolutionTime + 15778800), "Must wait 6 months for Augur Oracle"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice Same as above, except that only I can call it, and I can call it whenever /// @notice to be clear, this only allows me to return all funds. I can not set a winner. function step1CcircuitBreaker() external { require(marketsResolved == false, "Step1 can only be completed once"); require(msg.sender == andrewsAddress, "Only owner can call this"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice the second of the three functions which must be called, one after the other, to conclude the competition /// @dev gets funds back from Augur, gets the available funds for distribution /// @dev can be called by anyone, but only once function step2withdrawFromAugur() external { require(marketsResolved == true, "Must wait for market resolution"); require(step2Complete == false, "Step2 should only be run once"); step2Complete = true; uint256 _balanceBefore = _getContractsCashBalance(); _augurWithdraw(); uint256 _balanceAfter = _getContractsCashBalance(); // daiAvailableToDistribute therefore does not include unused deposits daiAvailableToDistribute = _balanceAfter.sub(_balanceBefore); emit LogStep2Complete(daiAvailableToDistribute); } /// @notice the final of the three functions which must be called, one after the other, to conclude the competition /// @notice pays me my 1% if markets resolved correctly. If not I don't deserve shit /// @dev this was originally included within step3 but it was modifed so that ineraction with Dai contract happened at the end function step3payAndrew() external { require(step2Complete == true, "Must wait for market resolution"); require(step3Complete == false, "Step3 should only be run once"); step3Complete = true; if (marketsResolvedWithoutErrors) { uint256 _andrewsWellEarntMonies = daiAvailableToDistribute.div(100); daiAvailableToDistribute = daiAvailableToDistribute.sub(_andrewsWellEarntMonies); _sendCash(andrewsAddress,_andrewsWellEarntMonies); emit LogAndrewPaid(_andrewsWellEarntMonies); } } /// @notice the final function of the competition resolution process. Pays out winnings, or returns funds, as necessary /// @dev users pull dai into their account. Replaces previous push vesion which required looping over unbounded mapping. function complete() external { require(step3Complete == true, "Step3 must be completed first"); if (marketsResolvedWithoutErrors) { _payoutWinnings(); } else { _returnRent(); } } // * internal * /// @notice pays winnings to the winners /// @dev must be internal and only called by complete function _payoutWinnings() internal { uint256 _winnersTimeHeld = timeHeld[winningOutcome][msg.sender]; if (_winnersTimeHeld > 0) { timeHeld[winningOutcome][msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_winnersTimeHeld); uint256 _winningsToTransfer = _numerator.div(totalTimeHeld[winningOutcome]); _sendCash(msg.sender, _winningsToTransfer); emit LogWinningsPaid(msg.sender, _winningsToTransfer); } } // * internal * /// @notice returns all funds to users in case of invalid outcome /// @dev must be internal and only called by complete function _returnRent() internal { uint256 _rentCollected = collectedPerUser[msg.sender]; if (_rentCollected > 0) { collectedPerUser[msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_rentCollected); uint256 _rentToToReturn = _numerator.div(totalCollected); _sendCash(msg.sender, _rentToToReturn); emit LogRentReturned(msg.sender, _rentToToReturn); } } /// @notice withdraw full deposit after markets have resolved /// @dev the other withdraw deposit functions are locked when markets have resolved so must use this one /// @dev ... which can only be called if markets have resolved. This function is also different in that it does /// @dev ... not attempt to collect rent or transfer ownership to a previous owner function withdrawDepositAfterResolution() external { require(marketsResolved == true, "step1 must be completed first"); for (uint i = 0; i < numberOfTokens; i++) { uint256 _depositToReturn = deposits[i][msg.sender]; if (_depositToReturn > 0) { deposits[i][msg.sender] = 0; _sendCash(msg.sender, _depositToReturn); emit LogDepositWithdrawal(_depositToReturn, i, msg.sender); } } } ////////////// ORDINARY COURSE OF BUSINESS FUNCTIONS ////////////// /// @notice collects rent for all tokens /// @dev makes it easy for me to call whenever I want to keep people paying their rent, thus cannot be internal /// @dev cannot be external because it is called within the step1 functions, therefore public function collectRentAllTokens() public notResolved() { for (uint i = 0; i < numberOfTokens; i++) { _collectRent(i); } } /// @notice collects rent for a specific token /// @dev also calculates and updates how long the current user has held the token for /// @dev called frequently internally, so cant be external. /// @dev is not a problem if called externally, but making internal to save gas function _collectRent(uint256 _tokenId) internal notResolved() { //only collect rent if the token is owned (ie, if owned by the contract this implies unowned) if (team.ownerOf(_tokenId) != address(this)) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); uint256 _timeOfThisCollection; if (_rentOwed >= deposits[_tokenId][_currentOwner]) { // run out of deposit. Calculate time it was actually paid for, then revert to previous owner _timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(deposits[_tokenId][_currentOwner]).div(_rentOwed))); _rentOwed = deposits[_tokenId][_currentOwner]; // take what's left _revertToPreviousOwner(_tokenId); } else { // normal collection _timeOfThisCollection = now; } // decrease deposit by rent owed deposits[_tokenId][_currentOwner] = deposits[_tokenId][_currentOwner].sub(_rentOwed); // the 'important bit', where the duration the token has been held by each user is updated // it is essential that timeHeld and totalTimeHeld are incremented together such that the sum of // the first is equal to the second uint256 _timeHeldToIncrement = (_timeOfThisCollection.sub(timeLastCollected[_tokenId])); //just for readability timeHeld[_tokenId][_currentOwner] = timeHeld[_tokenId][_currentOwner].add(_timeHeldToIncrement); totalTimeHeld[_tokenId] = totalTimeHeld[_tokenId].add(_timeHeldToIncrement); // it is also essential that collectedPerUser and totalCollected are all incremented together // such that the sum of the first two (individually) is equal to the third collectedPerUser[_currentOwner] = collectedPerUser[_currentOwner].add(_rentOwed); totalCollected = totalCollected.add(_rentOwed); _augurDeposit(_rentOwed); emit LogRentCollection(_rentOwed, _tokenId); } // timeLastCollected is updated regardless of whether the token is owned, so that the clock starts ticking // ... when the first owner buys it, because this function is run before ownership changes upon calling // ... newRental timeLastCollected[_tokenId] = now; } /// @notice to rent a token function newRental(uint256 _newPrice, uint256 _tokenId, uint256 _deposit) external tokenExists(_tokenId) amountNotZero(_deposit) notResolved() { require(_newPrice > price[_tokenId], "Price must be higher than current price"); _collectRent(_tokenId); // require(1==2, "STFU"); address _currentOwner = team.ownerOf(_tokenId); if (_currentOwner == msg.sender) { // bought by current owner (ie, token ownership does not change, so it is as if the current owner // ... called changePrice and depositDai seperately) _changePrice(_newPrice, _tokenId); _depositDai(_deposit, _tokenId); } else { // bought by different user (the normal situation) // deposits are updated via depositDai function if _currentOwner = msg.sender // therefore deposits only updated inside this else section deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_deposit); // update currentOwnerIndex and ownerTracker currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].add(1); ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].owner = msg.sender; // update timeAcquired for the front end timeAcquired[_tokenId] = now; _transferTokenTo(_currentOwner, msg.sender, _newPrice, _tokenId); _receiveCash(msg.sender, _deposit); emit LogNewRental(msg.sender, _newPrice, _tokenId); } } /// @notice add new dai deposit to an existing rental /// @dev it is possible a user's deposit could be reduced to zero following _collectRent /// @dev they would then increase their deposit despite no longer owning it /// @dev this is ok, they can withdraw via withdrawDeposit. function depositDai(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); _depositDai(_dai, _tokenId); } /// @dev depositDai is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _depositDai(uint256 _dai, uint256 _tokenId) internal { deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_dai); _receiveCash(msg.sender, _dai); emit LogDepositIncreased(_dai, _tokenId, msg.sender); } /// @notice increase the price of an existing rental /// @dev can't be external because also called within newRental function changePrice(uint256 _newPrice, uint256 _tokenId) public tokenExists(_tokenId) notResolved() { require(_newPrice > price[_tokenId], "New price must be higher than current price"); require(msg.sender == team.ownerOf(_tokenId), "Not owner"); _collectRent(_tokenId); _changePrice(_newPrice, _tokenId); } /// @dev changePrice is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _changePrice(uint256 _newPrice, uint256 _tokenId) internal { // below is the only instance when price is modifed outside of the _transferTokenTo function price[_tokenId] = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; emit LogPriceChange(price[_tokenId], _tokenId); } /// @notice withdraw deposit /// @dev do not need to be the current owner function withdrawDeposit(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() returns (uint256) { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(_dai, _tokenId); emit LogDepositWithdrawal(_dai, _tokenId, msg.sender); } } /// @notice withdraw full deposit /// @dev do not need to be the current owner function exit(uint256 _tokenId) external tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent modifier if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(deposits[_tokenId][msg.sender], _tokenId); emit LogExit(_tokenId); } } /* internal */ /// @notice actually withdraw the deposit and call _revertToPreviousOwner if necessary function _withdrawDeposit(uint256 _dai, uint256 _tokenId) internal { require(deposits[_tokenId][msg.sender] >= _dai, 'Withdrawing too much'); deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].sub(_dai); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender && deposits[_tokenId][msg.sender] == 0) { _revertToPreviousOwner(_tokenId); } _sendCash(msg.sender, _dai); } /* internal */ /// @notice if a users deposit runs out, either return to previous owner or foreclose function _revertToPreviousOwner(uint256 _tokenId) internal { bool _reverted = false; bool _toForeclose = false; uint256 _index; address _previousOwner; while (_reverted == false) { assert(currentOwnerIndex[_tokenId] >=0); currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].sub(1); // currentOwnerIndex will now point to previous owner _index = currentOwnerIndex[_tokenId]; // just for readability _previousOwner = ownerTracker[_tokenId][_index].owner; //if no previous owners. price -> zero, foreclose //if previous owner still has a deposit, transfer to them, update the price to what it used to be if (_index == 0) { _toForeclose = true; _reverted = true; } else if (deposits[_tokenId][_previousOwner] > 0) { _reverted = true; } } if (_toForeclose) { _foreclose(_tokenId); } else { address _currentOwner = team.ownerOf(_tokenId); uint256 _oldPrice = ownerTracker[_tokenId][_index].price; _transferTokenTo(_currentOwner, _previousOwner, _oldPrice, _tokenId); emit LogReturnToPreviousOwner(_tokenId, _previousOwner); } } /* internal */ /// @notice return token to the contract and return price to zero function _foreclose(uint256 _tokenId) internal { address _currentOwner = team.ownerOf(_tokenId); // third field is price, ie price goes to zero _transferTokenTo(_currentOwner, address(this), 0, _tokenId); emit LogForeclosure(_currentOwner, _tokenId); } /* internal */ /// @notice transfer ERC 721 between users /// @dev there is no event emitted as this is handled in ERC721.sol function _transferTokenTo(address _currentOwner, address _newOwner, uint256 _newPrice, uint256 _tokenId) internal { require(_currentOwner != address(0) && _newOwner != address(0) , "Cannot send to/from zero address"); team.transferFrom(_currentOwner, _newOwner, _tokenId); price[_tokenId] = _newPrice; } }
@notice add new dai deposit to an existing rental @dev it is possible a user's deposit could be reduced to zero following _collectRent @dev they would then increase their deposit despite no longer owning it @dev this is ok, they can withdraw via withdrawDeposit.
function depositDai(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); _depositDai(_dai, _tokenId); }
15,828,486
[ 1, 1289, 394, 5248, 77, 443, 1724, 358, 392, 2062, 283, 496, 287, 225, 518, 353, 3323, 279, 729, 1807, 443, 1724, 3377, 506, 13162, 358, 3634, 3751, 389, 14676, 54, 319, 225, 2898, 4102, 1508, 10929, 3675, 443, 1724, 2832, 84, 1137, 1158, 7144, 25022, 518, 225, 333, 353, 1529, 16, 2898, 848, 598, 9446, 3970, 598, 9446, 758, 1724, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 40, 10658, 12, 11890, 5034, 389, 2414, 77, 16, 2254, 5034, 389, 2316, 548, 13, 3903, 3844, 1248, 7170, 24899, 2414, 77, 13, 1147, 4002, 24899, 2316, 548, 13, 486, 12793, 1435, 288, 203, 3639, 389, 14676, 54, 319, 24899, 2316, 548, 1769, 203, 3639, 389, 323, 1724, 40, 10658, 24899, 2414, 77, 16, 389, 2316, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; // File: contracts/ds-auth/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.4.24; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // File: contracts/AssetPriceOracle.sol contract AssetPriceOracle is DSAuth { // Maximum value expressible with uint128 is 340282366920938463463374607431768211456. // Using 18 decimals for price records (standard Ether precision), // the possible values are between 0 and 340282366920938463463.374607431768211456. struct AssetPriceRecord { uint128 price; bool isRecord; } mapping(uint128 => mapping(uint128 => AssetPriceRecord)) public assetPriceRecords; event AssetPriceRecorded( uint128 indexed assetId, uint128 indexed blockNumber, uint128 indexed price ); constructor() public { } function recordAssetPrice(uint128 assetId, uint128 blockNumber, uint128 price) public auth { assetPriceRecords[assetId][blockNumber].price = price; assetPriceRecords[assetId][blockNumber].isRecord = true; emit AssetPriceRecorded(assetId, blockNumber, price); } function getAssetPrice(uint128 assetId, uint128 blockNumber) public view returns (uint128 price) { AssetPriceRecord storage priceRecord = assetPriceRecords[assetId][blockNumber]; require(priceRecord.isRecord); return priceRecord.price; } function () public { // dont receive ether via fallback method (by not having 'payable' modifier on this function). } } // File: contracts/lib/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error * Source: https://github.com/facuspagnuolo/zeppelin-solidity/blob/feature/705_add_safe_math_int_ops/contracts/math/SafeMath.sol */ library SafeMath { /** * @dev Multiplies two unsigned integers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Multiplies two signed integers, throws on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } int256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two unsigned integers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Integer division of two signed integers, truncating the quotient. */ function div(int256 a, int256 b) internal pure returns (int256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // Overflow only happens when the smallest negative int is multiplied by -1. int256 INT256_MIN = int256((uint256(1) << 255)); assert(a != INT256_MIN || b != -1); return a / b; } /** * @dev Subtracts two unsigned integers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Subtracts two signed integers, throws on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; assert((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } /** * @dev Adds two signed integers, throws on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } // File: contracts/ContractForDifference.sol contract ContractForDifference is DSAuth { using SafeMath for int256; enum Position { Long, Short } /** * A party to the contract. Either the maker or the taker. */ struct Party { address addr; uint128 withdrawBalance; // Amount the Party can withdraw, as a result of settled contract. Position position; bool isPaid; } struct Cfd { Party maker; Party taker; uint128 assetId; uint128 amount; // in Wei. uint128 contractStartBlock; // Block number uint128 contractEndBlock; // Block number // CFD state variables bool isTaken; bool isSettled; bool isRefunded; } uint128 public leverage = 1; // Global leverage of the CFD contract. AssetPriceOracle public priceOracle; mapping(uint128 => Cfd) public contracts; uint128 public numberOfContracts; event LogMakeCfd ( uint128 indexed cfdId, address indexed makerAddress, Position indexed makerPosition, uint128 assetId, uint128 amount, uint128 contractEndBlock); event LogTakeCfd ( uint128 indexed cfdId, address indexed makerAddress, Position makerPosition, address indexed takerAddress, Position takerPosition, uint128 assetId, uint128 amount, uint128 contractStartBlock, uint128 contractEndBlock); event LogCfdSettled ( uint128 indexed cfdId, address indexed makerAddress, address indexed takerAddress, uint128 amount, uint128 startPrice, uint128 endPrice, uint128 makerSettlement, uint128 takerSettlement); event LogCfdRefunded ( uint128 indexed cfdId, address indexed makerAddress, uint128 amount); event LogCfdForceRefunded ( uint128 indexed cfdId, address indexed makerAddress, uint128 makerAmount, address indexed takerAddress, uint128 takerAmount); event LogWithdrawal ( uint128 indexed cfdId, address indexed withdrawalAddress, uint128 amount); // event Debug ( // string description, // uint128 uintValue, // int128 intValue // ); constructor(address priceOracleAddress) public { priceOracle = AssetPriceOracle(priceOracleAddress); } function makeCfd( address makerAddress, uint128 assetId, Position makerPosition, uint128 contractEndBlock ) public payable returns (uint128) { require(contractEndBlock > block.number); // Contract end block must be after current block. require(msg.value > 0); // Contract Wei amount must be more than zero - contracts for zero Wei does not make sense. require(makerAddress != address(0)); // Maker must provide a non-zero address. uint128 contractId = numberOfContracts; /** * Initialize CFD struct using tight variable packing pattern. * See https://fravoll.github.io/solidity-patterns/tight_variable_packing.html */ Party memory maker = Party(makerAddress, 0, makerPosition, false); Party memory taker = Party(address(0), 0, Position.Long, false); Cfd memory newCfd = Cfd( maker, taker, assetId, uint128(msg.value), 0, contractEndBlock, false, false, false ); contracts[contractId] = newCfd; // contracts[contractId].maker.addr = makerAddress; // contracts[contractId].maker.position = makerPosition; // contracts[contractId].assetId = assetId; // contracts[contractId].amount = uint128(msg.value); // contracts[contractId].contractEndBlock = contractEndBlock; numberOfContracts++; emit LogMakeCfd( contractId, contracts[contractId].maker.addr, contracts[contractId].maker.position, contracts[contractId].assetId, contracts[contractId].amount, contracts[contractId].contractEndBlock ); return contractId; } function getCfd( uint128 cfdId ) public view returns (address makerAddress, Position makerPosition, address takerAddress, Position takerPosition, uint128 assetId, uint128 amount, uint128 startTime, uint128 endTime, bool isTaken, bool isSettled, bool isRefunded) { Cfd storage cfd = contracts[cfdId]; return ( cfd.maker.addr, cfd.maker.position, cfd.taker.addr, cfd.taker.position, cfd.assetId, cfd.amount, cfd.contractStartBlock, cfd.contractEndBlock, cfd.isTaken, cfd.isSettled, cfd.isRefunded ); } function takeCfd( uint128 cfdId, address takerAddress ) public payable returns (bool success) { Cfd storage cfd = contracts[cfdId]; require(cfd.isTaken != true); // Contract must not be taken. require(cfd.isSettled != true); // Contract must not be settled. require(cfd.isRefunded != true); // Contract must not be refunded. require(cfd.maker.addr != address(0)); // Contract must have a maker, require(cfd.taker.addr == address(0)); // and no taker. // require(takerAddress != cfd.maker.addr); // Maker and Taker must not be the same address. (disabled for now) require(msg.value == cfd.amount); // Takers deposit must match makers deposit. require(takerAddress != address(0)); // Taker must provide a non-zero address. require(block.number <= cfd.contractEndBlock); // Taker must take contract before end block. cfd.taker.addr = takerAddress; // Make taker position the inverse of maker position cfd.taker.position = cfd.maker.position == Position.Long ? Position.Short : Position.Long; cfd.contractStartBlock = uint128(block.number); cfd.isTaken = true; emit LogTakeCfd( cfdId, cfd.maker.addr, cfd.maker.position, cfd.taker.addr, cfd.taker.position, cfd.assetId, cfd.amount, cfd.contractStartBlock, cfd.contractEndBlock ); return true; } function settleAndWithdrawCfd( uint128 cfdId ) public { address makerAddr = contracts[cfdId].maker.addr; address takerAddr = contracts[cfdId].taker.addr; settleCfd(cfdId); withdraw(cfdId, makerAddr); withdraw(cfdId, takerAddr); } function settleCfd( uint128 cfdId ) public returns (bool success) { Cfd storage cfd = contracts[cfdId]; require(cfd.contractEndBlock <= block.number); // Contract must have met its end time. require(!cfd.isSettled); // Contract must not be settled already. require(!cfd.isRefunded); // Contract must not be refunded. require(cfd.isTaken); // Contract must be taken. require(cfd.maker.addr != address(0)); // Contract must have a maker address. require(cfd.taker.addr != address(0)); // Contract must have a taker address. // Get relevant variables uint128 amount = cfd.amount; uint128 startPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractStartBlock); uint128 endPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractEndBlock); /** * Register settlements for maker and taker. * Maker recieves any leftover wei from integer division. */ uint128 takerSettlement = getSettlementAmount(amount, startPrice, endPrice, cfd.taker.position); if (takerSettlement > 0) { cfd.taker.withdrawBalance = takerSettlement; } uint128 makerSettlement = (amount * 2) - takerSettlement; cfd.maker.withdrawBalance = makerSettlement; // Mark contract as settled. cfd.isSettled = true; emit LogCfdSettled ( cfdId, cfd.maker.addr, cfd.taker.addr, amount, startPrice, endPrice, makerSettlement, takerSettlement ); return true; } function withdraw( uint128 cfdId, address partyAddress ) public { Cfd storage cfd = contracts[cfdId]; Party storage party = partyAddress == cfd.maker.addr ? cfd.maker : cfd.taker; require(party.withdrawBalance > 0); // The party must have a withdraw balance from previous settlement. require(!party.isPaid); // The party must have already been paid out, fx from a refund. uint128 amount = party.withdrawBalance; party.withdrawBalance = 0; party.isPaid = true; party.addr.transfer(amount); emit LogWithdrawal( cfdId, party.addr, amount ); } function getSettlementAmount( uint128 amountUInt, uint128 entryPriceUInt, uint128 exitPriceUInt, Position position ) public view returns (uint128) { require(position == Position.Long || position == Position.Short); // If price didn't change, settle for equal amount to long and short. if (entryPriceUInt == exitPriceUInt) {return amountUInt;} // If entry price is 0 and exit price is more than 0, all must go to long position and nothing to short. if (entryPriceUInt == 0 && exitPriceUInt > 0) { return position == Position.Long ? amountUInt * 2 : 0; } // Cast uint128 to int256 to support negative numbers and increase over- and underflow limits int256 entryPrice = int256(entryPriceUInt); int256 exitPrice = int256(exitPriceUInt); int256 amount = int256(amountUInt); // Price diff calc depends on which position we are calculating settlement for. int256 priceDiff = position == Position.Long ? exitPrice.sub(entryPrice) : entryPrice.sub(exitPrice); int256 settlement = amount.add(priceDiff.mul(amount).mul(leverage).div(entryPrice)); if (settlement < 0) { return 0; // Calculated settlement was negative. But a party can't lose more than his deposit, so he's just awarded 0. } else if (settlement > amount * 2) { return amountUInt * 2; // Calculated settlement was more than the total deposits, so settle for the total deposits. } else { return uint128(settlement); // Settlement was more than zero and less than sum of deposit amounts, so we can settle it as is. } } function refundCfd( uint128 cfdId ) public returns (bool success) { Cfd storage cfd = contracts[cfdId]; require(!cfd.isSettled); // Contract must not be settled already. require(!cfd.isTaken); // Contract must not be taken. require(!cfd.isRefunded); // Contract must not be refunded already. require(msg.sender == cfd.maker.addr); // Function caller must be the contract maker. cfd.isRefunded = true; cfd.maker.isPaid = true; cfd.maker.addr.transfer(cfd.amount); emit LogCfdRefunded( cfdId, cfd.maker.addr, cfd.amount ); return true; } function forceRefundCfd( uint128 cfdId ) public auth { Cfd storage cfd = contracts[cfdId]; require(!cfd.isRefunded); // Contract must not be refunded already. cfd.isRefunded = true; // Refund Taker uint128 takerAmount = 0; if (cfd.taker.addr != address(0)) { takerAmount = cfd.amount; cfd.taker.withdrawBalance = 0; // Refunding must reset withdraw balance, if any. cfd.taker.addr.transfer(cfd.amount); } // Refund Maker cfd.maker.withdrawBalance = 0; // Refunding must reset withdraw balance, if any. cfd.maker.addr.transfer(cfd.amount); emit LogCfdForceRefunded( cfdId, cfd.maker.addr, cfd.amount, cfd.taker.addr, takerAmount ); } function () public { // dont receive ether via fallback method (by not having 'payable' modifier on this function). } }
Contract must not be refunded already.
require(!cfd.isRefunded);
12,680,595
[ 1, 8924, 1297, 486, 506, 1278, 12254, 1818, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 5, 71, 8313, 18, 291, 1957, 12254, 1769, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/10/0x9bf586ceB3F3C1bebBE8b0262c2AE7D0952ce3B1/sources/src/zkbob/ZkBobDirectDepositQueue.sol
small amount of wei might get lost during division, this amount will stay in the contract indefinitely
function _recordDirectDeposit( address _sender, address _fallbackReceiver, uint256 _amount, bytes memory _rawZkAddress ) internal returns (uint256 nonce) { require(_fallbackReceiver != address(0), "ZkBobDirectDepositQueue: fallback user is zero"); uint64 fee = directDepositFee; uint64 depositAmount = uint64(_amount / TOKEN_DENOMINATOR * TOKEN_NUMERATOR); require(depositAmount > fee, "ZkBobDirectDepositQueue: direct deposit amount is too low"); unchecked { depositAmount -= fee; } ZkAddress.ZkAddress memory zkAddress = ZkAddress.parseZkAddress(_rawZkAddress, uint24(pool_id)); IZkBobDirectDeposits.DirectDeposit memory dd = IZkBobDirectDeposits.DirectDeposit({ fallbackReceiver: _fallbackReceiver, sent: uint96(_amount), deposit: depositAmount, fee: fee, timestamp: uint40(block.timestamp), status: DirectDepositStatus.Pending, diversifier: zkAddress.diversifier, pk: zkAddress.pk }); nonce = directDepositNonce++; directDeposits[nonce] = dd; IZkBobPool(pool).recordDirectDeposit(_sender, depositAmount); emit SubmitDirectDeposit(_sender, nonce, _fallbackReceiver, zkAddress, depositAmount); }
3,532,685
[ 1, 12019, 3844, 434, 732, 77, 4825, 336, 13557, 4982, 16536, 16, 333, 3844, 903, 23449, 316, 326, 6835, 316, 536, 2738, 2357, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 3366, 5368, 758, 1724, 12, 203, 3639, 1758, 389, 15330, 16, 203, 3639, 1758, 389, 16471, 12952, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1731, 3778, 389, 1899, 62, 79, 1887, 203, 565, 262, 203, 3639, 2713, 203, 3639, 1135, 261, 11890, 5034, 7448, 13, 203, 565, 288, 203, 3639, 2583, 24899, 16471, 12952, 480, 1758, 12, 20, 3631, 315, 62, 79, 38, 947, 5368, 758, 1724, 3183, 30, 5922, 729, 353, 3634, 8863, 203, 203, 3639, 2254, 1105, 14036, 273, 2657, 758, 1724, 14667, 31, 203, 3639, 2254, 1105, 443, 1724, 6275, 273, 2254, 1105, 24899, 8949, 342, 14275, 67, 13296, 1872, 706, 3575, 380, 14275, 67, 6069, 654, 3575, 1769, 203, 3639, 2583, 12, 323, 1724, 6275, 405, 14036, 16, 315, 62, 79, 38, 947, 5368, 758, 1724, 3183, 30, 2657, 443, 1724, 3844, 353, 4885, 4587, 8863, 203, 3639, 22893, 288, 203, 5411, 443, 1724, 6275, 3947, 14036, 31, 203, 3639, 289, 203, 203, 3639, 2285, 79, 1887, 18, 62, 79, 1887, 3778, 14164, 1887, 273, 2285, 79, 1887, 18, 2670, 62, 79, 1887, 24899, 1899, 62, 79, 1887, 16, 2254, 3247, 12, 6011, 67, 350, 10019, 203, 203, 3639, 467, 62, 79, 38, 947, 5368, 758, 917, 1282, 18, 5368, 758, 1724, 3778, 6957, 273, 467, 62, 79, 38, 947, 5368, 758, 917, 1282, 18, 5368, 758, 1724, 12590, 203, 5411, 5922, 12952, 30, 389, 16471, 12952, 16, 203, 5411, 3271, 30, 2254, 10525, 24899, 8949, 3631, 203, 5411, 443, 1724, 30, 443, 1724, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./interfaces/IRegistry.sol"; import "./Space.sol"; contract RegistryLogic is IRegistry { struct bakAddressInfo { address bakAddress; uint64 startTime; } address private owner; //placeholder address private registerLogic; //placeholder address private defaultGuardian; //placeholder address private spaceLogic; //placeholder uint64 latencyTime; //placeholder mapping(address => bytes32) private ownerToName; mapping(bytes32 => address) private nameToOwner; mapping(address => address) private ownerToSuccessor; mapping(address => bakAddressInfo) private ownerToSuccessorBak; mapping(address => address) private ownerToGuardian; mapping(address => bakAddressInfo) private ownerToGuardianBak; mapping(bytes32 => address) public spaceTable; //not support change name function register(bytes32 accountName, address successor, address guardian) external override returns (bool) { if (nameToOwner[accountName] == address(0)) { nameToOwner[accountName] = msg.sender; ownerToName[msg.sender] = accountName; ownerToSuccessor[msg.sender] = successor; ownerToGuardian[msg.sender] = guardian; address spaceAddr = newSpace(accountName, msg.sender); spaceTable[accountName] = spaceAddr; emit Register(accountName, msg.sender, successor, guardian); return true; } return false; } //by owner, guardian function switchOwner(bytes32 accountName) external override { address _owner = nameToOwner[accountName]; bakAddressInfo memory guardianInfo = ownerToGuardianBak[_owner]; address _guardian; if (guardianInfo.startTime > 0 && block.timestamp > latencyTime + guardianInfo.startTime) { _guardian = guardianInfo.bakAddress; ownerToGuardian[_owner] = _guardian; delete ownerToGuardianBak[_owner]; } else { _guardian = ownerToGuardian[_owner]; } require(_owner != address(0) && (_owner == msg.sender || _guardian == msg.sender || (_guardian == address(0) && defaultGuardian == msg.sender))); bakAddressInfo memory info = ownerToSuccessorBak[_owner]; address _successor; if (info.startTime > 0 && block.timestamp > latencyTime + info.startTime) { _successor = info.bakAddress; delete ownerToSuccessorBak[_owner]; } else { _successor = ownerToSuccessor[_owner]; } nameToOwner[accountName] = _successor; ownerToName[_successor] = accountName; delete ownerToName[_owner]; address space = spaceTable[accountName]; if (space != address(0)) { IMySpace(space).switchToNewOwner(_successor); } emit SwitchOwner(accountName, _successor); } function setSuccessor(address _successor) external override { bakAddressInfo memory info; info.bakAddress = _successor; info.startTime = uint64(block.timestamp); ownerToSuccessorBak[msg.sender] = info; } function setGuardian(address _guardian) external override { bakAddressInfo memory info; info.bakAddress = _guardian; info.startTime = uint64(block.timestamp); ownerToGuardianBak[msg.sender] = info; } // Given the owner's address, query the corresponding accountName function getAccountNameByOwner(address _owner) external view override returns (bytes32) { return ownerToName[_owner]; } // Given the accountName, query the addresses of the owner and operator function getOwnerByAccountName(bytes32 accountName) external view override returns (address) { return nameToOwner[accountName]; } // Given the accountName, query the newly-appointed operator function getSuccessor(address _owner) external view override returns (address) { return ownerToSuccessor[_owner]; } function getGuardian(address _owner) external view override returns (address) { return ownerToGuardian[_owner]; } function getDefaultGuardian() external view override returns (address) { return defaultGuardian; } function setSpace(address _newLogic) external override { require(msg.sender == owner); spaceLogic = _newLogic; } function getSpaceLogic() external view override returns (address) { return spaceLogic; } // Create Space, only owner function newSpace(bytes32 accountName, address _owner) internal returns (address) { //call Space contract bytes32 salt = keccak256(abi.encode(accountName)); Space space = new Space{salt : salt}(_owner, address(this)); return address(space); } function getSpaceByAccountName(bytes32 accountName) external view override returns (address) { return spaceTable[accountName]; } function getSpaceByOwner(address _owner) external view override returns (address) { bytes32 accountName = ownerToName[_owner]; return spaceTable[accountName]; } }
Given the owner's address, query the corresponding accountName
function getAccountNameByOwner(address _owner) external view override returns (bytes32) { return ownerToName[_owner]; }
12,886,305
[ 1, 6083, 326, 3410, 1807, 1758, 16, 843, 326, 4656, 15862, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 14498, 858, 5541, 12, 2867, 389, 8443, 13, 3903, 1476, 3849, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 3410, 774, 461, 63, 67, 8443, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.4; contract Ownable { address payable _owner; //assigns owner to person deploying contract constructor() public { _owner = msg.sender; } modifier onlyOwner() { require(isOwner(), "You're not the Owner!!"); _; } //verifies if address is the owner function isOwner() public view returns(bool) { return (msg.sender == _owner); } }
verifies if address is the owner
function isOwner() public view returns(bool) { return (msg.sender == _owner); }
5,346,492
[ 1, 502, 5032, 309, 1758, 353, 326, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 327, 261, 3576, 18, 15330, 422, 389, 8443, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xe62fAF59BD7BF333aC80006d5C5bD7F3D0a8f21D/sources/Implementation.sol
Chain */ Bootstrapping */ Oracle */ Bonding */ Epoch */
struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1609539545; uint256 private constant EPOCH_PERIOD = 14400;
4,167,823
[ 1, 3893, 342, 11830, 1382, 342, 28544, 342, 605, 1434, 310, 342, 512, 6127, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 512, 6127, 4525, 288, 203, 3639, 2254, 5034, 1384, 31, 203, 3639, 2254, 5034, 787, 31, 203, 3639, 2254, 5034, 3879, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 11271, 273, 374, 31, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 7570, 273, 2872, 5908, 25, 5520, 6564, 25, 31, 203, 565, 2254, 5034, 3238, 5381, 512, 30375, 67, 28437, 273, 5045, 16010, 31, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x1502d025BfA624469892289D45C0352997251728/sources/contracts/libraries/TwoPower.sol
@title FixedPoint128 @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library TwoPower { uint256 internal constant pow96 = 0x1000000000000000000000000; uint256 internal constant pow128 = 0x100000000000000000000000000000000; uint8 internal constant RESOLUTION = 96; pragma solidity ^0.8.4; }
11,547,023
[ 1, 7505, 2148, 10392, 225, 432, 5313, 364, 5057, 3112, 5499, 1634, 5600, 16, 2621, 2333, 2207, 275, 18, 11999, 13744, 18, 3341, 19, 13044, 19, 53, 67, 12, 2696, 67, 2139, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 16896, 13788, 288, 203, 203, 565, 2254, 5034, 2713, 5381, 7602, 10525, 273, 374, 92, 21, 12648, 12648, 12648, 31, 203, 565, 2254, 5034, 2713, 5381, 7602, 10392, 273, 374, 92, 21, 12648, 12648, 12648, 12648, 31, 203, 565, 2254, 28, 2713, 5381, 12915, 1741, 13269, 273, 19332, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x47eBB1fef51820aF68457289274F760bf56B29A5/sources/MasterChef.sol
Safe lfi transfer function, just in case if rounding error causes pool to not have enough YFIGs.
function safeYFIGTransfer(address _to, uint256 _amount) internal { uint256 YFIGBal = YFIG.balanceOf(address(this)); if (_amount > YFIGBal) { YFIG.transfer(_to, YFIGBal); YFIG.transfer(_to, _amount); } }
11,254,118
[ 1, 9890, 18594, 77, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 1624, 5236, 87, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 61, 5236, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 1624, 5236, 38, 287, 273, 1624, 5236, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 1624, 5236, 38, 287, 13, 288, 203, 5411, 1624, 5236, 18, 13866, 24899, 869, 16, 1624, 5236, 38, 287, 1769, 203, 5411, 1624, 5236, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // Interface import { ILazyMintERC1155 } from "./ILazyMintERC1155.sol"; // Token import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; // Protocol control center. import { ProtocolControl } from "../../ProtocolControl.sol"; // Royalties import "@openzeppelin/contracts/interfaces/IERC2981.sol"; // Access Control + security import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; // Meta transactions import "@openzeppelin/contracts/metatx/ERC2771Context.sol"; // Utils import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; // Helper interfaces import { IWETH } from "../../interfaces/IWETH.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract LazyMintERC1155 is ILazyMintERC1155, ERC1155, ERC2771Context, IERC2981, AccessControlEnumerable, ReentrancyGuard, Multicall { using Strings for uint256; /// @dev Only TRANSFER_ROLE holders can have tokens transferred from or to them, during restricted transfers. bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); /// @dev Only MINTER_ROLE holders can lazy mint NFTs (i.e. can call functions prefixed with `lazyMint`). bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @dev The address interpreted as native token of the chain. address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev The address of the native token wrapper contract. address public immutable nativeTokenWrapper; /// @dev The adress that receives all primary sales value. address public defaultSaleRecipient; /// @dev The next token ID of the NFT to "lazy mint". uint256 public nextTokenIdToMint; /// @dev Contract interprets 10_000 as 100%. uint64 private constant MAX_BPS = 10_000; /// @dev The % of secondary sales collected as royalties. See EIP 2981. uint64 public royaltyBps; /// @dev The % of primary sales collected by the contract as fees. uint120 public feeBps; /// @dev Whether transfers on tokens are restricted. bool public transfersRestricted; /// @dev Contract level metadata. string public contractURI; /// @dev The protocol control center. ProtocolControl internal controlCenter; uint256[] private baseURIIndices; /// @dev End token Id => URI that overrides `baseURI + tokenId` convention. mapping(uint256 => string) private baseURI; /// @dev Token ID => total circulating supply of tokens with that ID. mapping(uint256 => uint256) public totalSupply; /// @dev Token ID => public claim conditions for tokens with that ID. mapping(uint256 => ClaimConditions) public claimConditions; /// @dev Token ID => the address of the recipient of primary sales. mapping(uint256 => address) public saleRecipient; /// @dev Checks whether caller has DEFAULT_ADMIN_ROLE on the protocol control center. modifier onlyProtocolAdmin() { require(controlCenter.hasRole(controlCenter.DEFAULT_ADMIN_ROLE(), _msgSender()), "not protocol admin."); _; } /// @dev Checks whether caller has DEFAULT_ADMIN_ROLE. modifier onlyModuleAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "not module admin."); _; } /// @dev Checks whether caller has MINTER_ROLE. modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "not minter."); _; } constructor( string memory _contractURI, address payable _controlCenter, address _trustedForwarder, address _nativeTokenWrapper, address _saleRecipient, uint128 _royaltyBps, uint128 _feeBps ) ERC1155("") ERC2771Context(_trustedForwarder) { controlCenter = ProtocolControl(_controlCenter); nativeTokenWrapper = _nativeTokenWrapper; defaultSaleRecipient = _saleRecipient; contractURI = _contractURI; royaltyBps = uint64(_royaltyBps); feeBps = uint120(_feeBps); address deployer = _msgSender(); _setupRole(DEFAULT_ADMIN_ROLE, deployer); _setupRole(MINTER_ROLE, deployer); _setupRole(TRANSFER_ROLE, deployer); } /// ===== Public functions ===== /// @dev Returns the URI for a given tokenId. function uri(uint256 _tokenId) public view override returns (string memory _tokenURI) { for (uint256 i = 0; i < baseURIIndices.length; i += 1) { if (_tokenId < baseURIIndices[i]) { return string(abi.encodePacked(baseURI[baseURIIndices[i]], _tokenId.toString())); } } return ""; } /// @dev Returns the URI for a given tokenId. function tokenURI(uint256 _tokenId) public view returns (string memory _tokenURI) { return uri(_tokenId); } /// @dev At any given moment, returns the uid for the active mint condition for a given tokenId. function getIndexOfActiveCondition(uint256 _tokenId) public view returns (uint256) { uint256 totalConditionCount = claimConditions[_tokenId].totalConditionCount; require(totalConditionCount > 0, "no public mint condition."); for (uint256 i = totalConditionCount; i > 0; i -= 1) { if (block.timestamp >= claimConditions[_tokenId].claimConditionAtIndex[i - 1].startTimestamp) { return i - 1; } } revert("no active mint condition."); } /// ===== External functions ===== /** * @dev Lets an account with `MINTER_ROLE` mint tokens of ID from `nextTokenIdToMint` * to `nextTokenIdToMint + _amount - 1`. The URIs for these tokenIds is baseURI + `${tokenId}`. */ function lazyMint(uint256 _amount, string calldata _baseURIForTokens) external onlyMinter { uint256 startId = nextTokenIdToMint; uint256 baseURIIndex = startId + _amount; nextTokenIdToMint = baseURIIndex; baseURI[baseURIIndex] = _baseURIForTokens; baseURIIndices.push(baseURIIndex); emit LazyMintedTokens(startId, startId + _amount - 1, _baseURIForTokens); } /// @dev Lets an account claim a given quantity of tokens, of a single tokenId. function claim( uint256 _tokenId, uint256 _quantity, bytes32[] calldata _proofs ) external payable nonReentrant { // Get the claim conditions. uint256 activeConditionIndex = getIndexOfActiveCondition(_tokenId); ClaimCondition memory condition = claimConditions[_tokenId].claimConditionAtIndex[activeConditionIndex]; // Verify claim validity. If not valid, revert. verifyClaimIsValid(_tokenId, _quantity, _proofs, activeConditionIndex, condition); // If there's a price, collect price. collectClaimPrice(condition, _quantity, _tokenId); // Mint the relevant tokens to claimer. transferClaimedTokens(activeConditionIndex, _tokenId, _quantity); emit ClaimedTokens(activeConditionIndex, _tokenId, _msgSender(), _quantity); } // @dev Lets a module admin update mint conditions without resetting the restrictions. function updateClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions) external onlyModuleAdmin { resetClaimConditions(_tokenId, _conditions); emit NewClaimConditions(_tokenId, _conditions); } /// @dev Lets a module admin set mint conditions. function setClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions) external onlyModuleAdmin { uint256 numOfConditionsSet = resetClaimConditions(_tokenId, _conditions); resetTimestampRestriction(_tokenId, numOfConditionsSet); emit NewClaimConditions(_tokenId, _conditions); } /// @dev See EIP 2981 function royaltyInfo(uint256, uint256 salePrice) external view virtual override returns (address receiver, uint256 royaltyAmount) { receiver = controlCenter.getRoyaltyTreasury(address(this)); royaltyAmount = (salePrice * royaltyBps) / MAX_BPS; } // ===== Setter functions ===== /// @dev Lets a module admin set the default recipient of all primary sales. function setDefaultSaleRecipient(address _saleRecipient) external onlyModuleAdmin { defaultSaleRecipient = _saleRecipient; emit NewSaleRecipient(_saleRecipient, type(uint256).max, true); } /// @dev Lets a module admin set the recipient of all primary sales for a given token ID. function setSaleRecipient(uint256 _tokenId, address _saleRecipient) external onlyModuleAdmin { saleRecipient[_tokenId] = _saleRecipient; emit NewSaleRecipient(_saleRecipient, _tokenId, false); } /// @dev Lets a module admin update the royalties paid on secondary token sales. function setRoyaltyBps(uint256 _royaltyBps) public onlyModuleAdmin { require(_royaltyBps <= MAX_BPS, "bps <= 10000."); royaltyBps = uint64(_royaltyBps); emit RoyaltyUpdated(_royaltyBps); } /// @dev Lets a module admin update the fees on primary sales. function setFeeBps(uint256 _feeBps) public onlyModuleAdmin { require(_feeBps <= MAX_BPS, "bps <= 10000."); feeBps = uint120(_feeBps); emit PrimarySalesFeeUpdates(_feeBps); } /// @dev Lets a module admin restrict token transfers. function setRestrictedTransfer(bool _restrictedTransfer) external onlyModuleAdmin { transfersRestricted = _restrictedTransfer; emit TransfersRestricted(_restrictedTransfer); } /// @dev Lets a module admin set the URI for contract-level metadata. function setContractURI(string calldata _uri) external onlyProtocolAdmin { contractURI = _uri; } // ===== Getter functions ===== /// @dev Returns the current active mint condition for a given tokenId. function getTimestampForNextValidClaim( uint256 _tokenId, uint256 _index, address _claimer ) public view returns (uint256 nextValidTimestampForClaim) { uint256 timestampIndex = _index + claimConditions[_tokenId].timstampLimitIndex; uint256 timestampOfLastClaim = claimConditions[_tokenId].timestampOfLastClaim[_claimer][timestampIndex]; unchecked { nextValidTimestampForClaim = timestampOfLastClaim + claimConditions[_tokenId].claimConditionAtIndex[_index].waitTimeInSecondsBetweenClaims; if (nextValidTimestampForClaim < timestampOfLastClaim) { nextValidTimestampForClaim = type(uint256).max; } } } /// @dev Returns the mint condition for a given tokenId, at the given index. function getClaimConditionAtIndex(uint256 _tokenId, uint256 _index) external view returns (ClaimCondition memory mintCondition) { mintCondition = claimConditions[_tokenId].claimConditionAtIndex[_index]; } // ===== Internal functions ===== /// @dev Lets a module admin set mint conditions for a given tokenId. function resetClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions) internal returns (uint256 indexForCondition) { // make sure the conditions are sorted in ascending order uint256 lastConditionStartTimestamp; for (uint256 i = 0; i < _conditions.length; i++) { require( lastConditionStartTimestamp == 0 || lastConditionStartTimestamp < _conditions[i].startTimestamp, "startTimestamp must be in ascending order." ); require(_conditions[i].maxClaimableSupply > 0, "max mint supply cannot be 0."); require(_conditions[i].quantityLimitPerTransaction > 0, "quantity limit cannot be 0."); claimConditions[_tokenId].claimConditionAtIndex[indexForCondition] = ClaimCondition({ startTimestamp: _conditions[i].startTimestamp, maxClaimableSupply: _conditions[i].maxClaimableSupply, supplyClaimed: 0, quantityLimitPerTransaction: _conditions[i].quantityLimitPerTransaction, waitTimeInSecondsBetweenClaims: _conditions[i].waitTimeInSecondsBetweenClaims, pricePerToken: _conditions[i].pricePerToken, currency: _conditions[i].currency, merkleRoot: _conditions[i].merkleRoot }); indexForCondition += 1; lastConditionStartTimestamp = _conditions[i].startTimestamp; } uint256 totalConditionCount = claimConditions[_tokenId].totalConditionCount; if (indexForCondition < totalConditionCount) { for (uint256 j = indexForCondition; j < totalConditionCount; j += 1) { delete claimConditions[_tokenId].claimConditionAtIndex[j]; } } claimConditions[_tokenId].totalConditionCount = indexForCondition; } /// @dev Updates the `timstampLimitIndex` to reset the time restriction between claims, for a claim condition. function resetTimestampRestriction(uint256 _tokenId, uint256 _factor) internal { claimConditions[_tokenId].timstampLimitIndex += _factor; } /// @dev Checks whether a request to claim tokens obeys the active mint condition. function verifyClaimIsValid( uint256 _tokenId, uint256 _quantity, bytes32[] calldata _proofs, uint256 _conditionIndex, ClaimCondition memory _mintCondition ) internal view { require(_quantity > 0 && _quantity <= _mintCondition.quantityLimitPerTransaction, "invalid quantity claimed."); require( _mintCondition.supplyClaimed + _quantity <= _mintCondition.maxClaimableSupply, "exceed max mint supply." ); uint256 timestampIndex = _conditionIndex + claimConditions[_tokenId].timstampLimitIndex; uint256 timestampOfLastClaim = claimConditions[_tokenId].timestampOfLastClaim[_msgSender()][timestampIndex]; uint256 nextValidTimestampForClaim = getTimestampForNextValidClaim(_tokenId, _conditionIndex, _msgSender()); require(timestampOfLastClaim == 0 || block.timestamp >= nextValidTimestampForClaim, "cannot claim yet."); if (_mintCondition.merkleRoot != bytes32(0)) { bytes32 leaf = keccak256(abi.encodePacked(_msgSender())); require(MerkleProof.verify(_proofs, _mintCondition.merkleRoot, leaf), "not in whitelist."); } } /// @dev Collects and distributes the primary sale value of tokens being claimed. function collectClaimPrice( ClaimCondition memory _mintCondition, uint256 _quantityToClaim, uint256 _tokenId ) internal { if (_mintCondition.pricePerToken <= 0) { return; } uint256 totalPrice = _quantityToClaim * _mintCondition.pricePerToken; uint256 fees = (totalPrice * feeBps) / MAX_BPS; if (_mintCondition.currency == NATIVE_TOKEN) { require(msg.value == totalPrice, "must send total price."); } else { validateERC20BalAndAllowance(_msgSender(), _mintCondition.currency, totalPrice); } transferCurrency(_mintCondition.currency, _msgSender(), controlCenter.getRoyaltyTreasury(address(this)), fees); address recipient = saleRecipient[_tokenId]; transferCurrency( _mintCondition.currency, _msgSender(), recipient == address(0) ? defaultSaleRecipient : recipient, totalPrice - fees ); } /// @dev Transfers the tokens being claimed. function transferClaimedTokens( uint256 _claimConditionIndex, uint256 _tokenId, uint256 _quantityBeingClaimed ) internal { // Update the supply minted under mint condition. claimConditions[_tokenId].claimConditionAtIndex[_claimConditionIndex].supplyClaimed += _quantityBeingClaimed; // Update the claimer's next valid timestamp to mint. If next mint timestamp overflows, cap it to max uint256. uint256 timestampIndex = _claimConditionIndex + claimConditions[_tokenId].timstampLimitIndex; claimConditions[_tokenId].timestampOfLastClaim[_msgSender()][timestampIndex] = block.timestamp; _mint(_msgSender(), _tokenId, _quantityBeingClaimed, ""); } /// @dev Transfers a given amount of currency. function transferCurrency( address _currency, address _from, address _to, uint256 _amount ) internal { if (_amount == 0) { return; } if (_currency == NATIVE_TOKEN) { if (_from == address(this)) { IWETH(nativeTokenWrapper).withdraw(_amount); safeTransferNativeToken(_to, _amount); } else if (_to == address(this)) { require(_amount == msg.value, "native token value does not match bid amount."); IWETH(nativeTokenWrapper).deposit{ value: _amount }(); } else { safeTransferNativeToken(_to, _amount); } } else { safeTransferERC20(_currency, _from, _to, _amount); } } /// @dev Validates that `_addrToCheck` owns and has approved contract to transfer the appropriate amount of currency function validateERC20BalAndAllowance( address _addrToCheck, address _currency, uint256 _currencyAmountToCheckAgainst ) internal view { require( IERC20(_currency).balanceOf(_addrToCheck) >= _currencyAmountToCheckAgainst && IERC20(_currency).allowance(_addrToCheck, address(this)) >= _currencyAmountToCheckAgainst, "insufficient currency balance or allowance." ); } /// @dev Transfers `amount` of native token to `to`. function safeTransferNativeToken(address to, uint256 value) internal { (bool success, ) = to.call{ value: value }(""); if (!success) { IWETH(nativeTokenWrapper).deposit{ value: value }(); safeTransferERC20(nativeTokenWrapper, address(this), to, value); } } /// @dev Transfer `amount` of ERC20 token from `from` to `to`. function safeTransferERC20( address _currency, address _from, address _to, uint256 _amount ) internal { if(_from == _to) { return; } uint256 balBefore = IERC20(_currency).balanceOf(_to); bool success = _from == address(this) ? IERC20(_currency).transfer(_to, _amount) : IERC20(_currency).transferFrom(_from, _to, _amount); uint256 balAfter = IERC20(_currency).balanceOf(_to); require(success && balAfter == balBefore + _amount, "failed to transfer currency."); } /// ===== ERC 1155 functions ===== /// @dev Lets a token owner burn the tokens they own (i.e. destroy for good) function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved." ); _burn(account, id, value); } /// @dev Lets a token owner burn multiple tokens they own at once (i.e. destroy for good) function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved." ); _burnBatch(account, ids, values); } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); // if transfer is restricted on the contract, we still want to allow burning and minting if (transfersRestricted && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } /// ===== Low level overrides ===== function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AccessControlEnumerable, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC2981).interfaceId; } function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) { return ERC2771Context._msgSender(); } function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) { return ERC2771Context._msgData(); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * `LazyMintERC1155` is an ERC 1155 contract. It takes in a base URI in its * constructor (e.g. "ipsf://Qmece.../"), and the URI for each token of ID * `tokenId` is baseURI + `${tokenId}` (e.g. "ipsf://Qmece.../1"). * * For each token with a unique ID, the module admin (account with `DEFAULT_ADMIN ROLE`) * can create mint conditions with non-overlapping time windows, and accounts can claim * the NFTs, in a given time window, according to that time window's mint conditions. */ interface ILazyMintERC1155 { /** * @notice The mint conditions for a given tokenId x time window. * * @param startTimestamp The unix timestamp after which the mint conditions last. * The same mint conditions last until the `startTimestamp` * of the next mint condition. * * @param maxClaimableSupply The maximum number of tokens of the same `tokenId` that can * be claimed under the mint condition. * * @param supplyClaimed At any given point, the number of tokens of the same `tokenId` * that have been claimed. * * @param quantityLimitPerTransaction The maximum number of tokens a single account can * claim in a single transaction. * * @param waitTimeInSecondsBetweenClaims The least number of seconds an account must wait * after claiming tokens, to be able to claim again. * * @param merkleRoot Only accounts whose address is a leaf of `merkleRoot` can claim tokens * under the mint condition. * * @param pricePerToken The price per token that can be claimed. * * @param currency The currency in which `pricePerToken` must be paid. */ struct ClaimCondition { uint256 startTimestamp; uint256 maxClaimableSupply; uint256 supplyClaimed; uint256 quantityLimitPerTransaction; uint256 waitTimeInSecondsBetweenClaims; bytes32 merkleRoot; uint256 pricePerToken; address currency; } /** * @notice The set of all mint conditions for a given tokenId. * * @dev In the contract, we use this in a mapping: tokenId => mint conditions i.e. * mapping(uint256 => PublicMintConditions) public mintConditions; * * @param totalConditionCount The uid for each mint condition. Incremented * by one every time a mint condition is created. * * @param claimConditionAtIndex The mint conditions at a given uid. Mint conditions * are ordered in an ascending order by their `startTimestamp`. * * @param nextValidTimestampForClaim Account => uid for a mint condition => timestamp after * which the account can claim tokens again. */ struct ClaimConditions { uint256 totalConditionCount; uint256 timstampLimitIndex; mapping(uint256 => ClaimCondition) claimConditionAtIndex; mapping(address => mapping(uint256 => uint256)) timestampOfLastClaim; } /// @dev Emitted when tokens are lazy minted. event LazyMintedTokens(uint256 startTokenId, uint256 endTokenId, string baseURI); /// @dev Emitted when tokens are claimed. event ClaimedTokens( uint256 indexed claimConditionIndex, uint256 indexed tokenId, address indexed claimer, uint256 quantityClaimed ); /// @dev Emitted when new mint conditions are set for a token. event NewClaimConditions(uint256 indexed tokenId, ClaimCondition[] claimConditions); /// @dev Emitted when a new sale recipient is set. event NewSaleRecipient(address indexed recipient, uint256 indexed _tokenId, bool isDefaultRecipient); /// @dev Emitted when the royalty fee bps is updated event RoyaltyUpdated(uint256 newRoyaltyBps); /// @dev Emitted when fee on primary sales is updated. event PrimarySalesFeeUpdates(uint256 newFeeBps); /// @dev Emitted when transfers are set as restricted / not-restricted. event TransfersRestricted(bool restricted); /// @dev The next token ID of the NFT to "lazy mint". function nextTokenIdToMint() external returns (uint256); /** * @notice Lets an account with `MINTER_ROLE` mint tokens of ID from `nextTokenIdToMint` * to `nextTokenIdToMint + _amount - 1`. The URIs for these tokenIds is baseURI + `${tokenId}`. * * @param _amount The amount of tokens (each with a unique tokenId) to lazy mint. */ function lazyMint(uint256 _amount, string calldata _baseURIForTokens) external; /** * @notice Lets an account claim a given quantity of tokens, of a single tokenId. * * @param _tokenId The unique ID of the token to claim. * @param _quantity The quantity of tokens to claim. * @param _proofs The proof required to prove the account's inclusion in the merkle root whitelist * of the mint conditions that apply. */ function claim( uint256 _tokenId, uint256 _quantity, bytes32[] calldata _proofs ) external payable; /** * @notice Lets a module admin (account with `DEFAULT_ADMIN_ROLE`) set mint conditions for a given token ID. * * @param _tokenId The token ID for which to set mint conditions. * @param _conditions Mint conditions in ascending order by `startTimestamp`. */ function setClaimConditions(uint256 _tokenId, ClaimCondition[] calldata _conditions) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // Access Control import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; // Registry import { Registry } from "./Registry.sol"; import { Royalty } from "./Royalty.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract ProtocolControl is AccessControlEnumerable, Multicall, Initializable { /// @dev Contract version string public constant version = "1"; /// @dev MAX_BPS for the contract: 10_000 == 100% uint256 public constant MAX_BPS = 10000; /// @dev The address interpreted as native token of the chain. address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Module ID => Module address. mapping(bytes32 => address) public modules; /// @dev Module type => Num of modules of that type. mapping(uint256 => uint256) public numOfModuleType; /// @dev module address => royalty address mapping(address => address) private moduleRoyalty; /// @dev The top level app registry. address public registry; /// @dev Deployer's treasury address public royaltyTreasury; /// @dev The Forwarder for this app's modules. address private _forwarder; /// @dev Contract level metadata. string public contractURI; /// @dev Events. event ModuleUpdated(bytes32 indexed moduleId, address indexed module); event TreasuryUpdated(address _newTreasury); event ForwarderUpdated(address _newForwarder); event FundsWithdrawn(address indexed to, address indexed currency, uint256 amount, uint256 fee); event EtherReceived(address from, uint256 amount); event RoyaltyTreasuryUpdated( address indexed protocolControlAddress, address indexed moduleAddress, address treasury ); /// @dev Check whether the caller is a protocol admin modifier onlyProtocolAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "ProtocolControl: Only protocol admins can call this function." ); _; } constructor() initializer {} function initialize( address _registry, address _admin, string memory _uri ) external initializer { // Set contract URI contractURI = _uri; // Set top level ap registry registry = _registry; // Set default royalty treasury address royaltyTreasury = address(this); // Set access control roles _setupRole(DEFAULT_ADMIN_ROLE, _admin); } /// @dev Lets the contract receive ether. receive() external payable { emit EtherReceived(msg.sender, msg.value); } /// @dev Initialize treasury payment royalty splitting pool function setRoyaltyTreasury(address payable _treasury) external onlyProtocolAdmin { require(_isRoyaltyTreasuryValid(_treasury), "ProtocolControl: provider shares too low."); royaltyTreasury = _treasury; emit RoyaltyTreasuryUpdated(address(this), address(0), _treasury); } /// @dev _treasury must be PaymentSplitter compatible interface. function setModuleRoyaltyTreasury(address moduleAddress, address payable _treasury) external onlyProtocolAdmin { require(_isRoyaltyTreasuryValid(_treasury), "ProtocolControl: provider shares too low."); moduleRoyalty[moduleAddress] = _treasury; emit RoyaltyTreasuryUpdated(address(this), moduleAddress, _treasury); } /// @dev validate to make sure protocol provider (the registry) gets enough fees. function _isRoyaltyTreasuryValid(address payable _treasury) private view returns (bool) { // Get `Royalty` and `Registry` instances Royalty royalty = Royalty(_treasury); Registry _registry = Registry(registry); // Calculate the protocol provider's shares. uint256 royaltyRegistryShares = royalty.shares(_registry.treasury()); uint256 royaltyTotalShares = royalty.totalShares(); uint256 registryCutBps = (royaltyRegistryShares * MAX_BPS) / royaltyTotalShares; // 10 bps (0.10%) tolerance in case of precision loss // making sure registry treasury gets at least the fee's worth of shares. uint256 feeBpsTolerance = 10; return registryCutBps >= (_registry.getFeeBps(address(this)) - feeBpsTolerance); } /// @dev Returns the Royalty payment splitter for a particular module. function getRoyaltyTreasury(address moduleAddress) external view returns (address) { address moduleRoyaltyTreasury = moduleRoyalty[moduleAddress]; if (moduleRoyaltyTreasury == address(0)) { return royaltyTreasury; } return moduleRoyaltyTreasury; } /// @dev Lets a protocol admin add a module to the protocol. function addModule(address _newModuleAddress, uint256 _moduleType) external onlyProtocolAdmin returns (bytes32 moduleId) { // `moduleId` is collision resitant -- unique `_moduleType` and incrementing `numOfModuleType` moduleId = keccak256(abi.encodePacked(numOfModuleType[_moduleType], _moduleType)); numOfModuleType[_moduleType] += 1; modules[moduleId] = _newModuleAddress; emit ModuleUpdated(moduleId, _newModuleAddress); } /// @dev Lets a protocol admin change the address of a module of the protocol. function updateModule(bytes32 _moduleId, address _newModuleAddress) external onlyProtocolAdmin { require(modules[_moduleId] != address(0), "ProtocolControl: a module with this ID does not exist."); modules[_moduleId] = _newModuleAddress; emit ModuleUpdated(_moduleId, _newModuleAddress); } /// @dev Sets contract URI for the contract-level metadata of the contract. function setContractURI(string calldata _URI) external onlyProtocolAdmin { contractURI = _URI; } /// @dev Lets the admin set a new Forwarder address [NOTE: for off-chain convenience only.] function setForwarder(address forwarder) external onlyProtocolAdmin { _forwarder = forwarder; emit ForwarderUpdated(forwarder); } /// @dev Returns all addresses for a module type function getAllModulesOfType(uint256 _moduleType) external view returns (address[] memory allModules) { uint256 numOfModules = numOfModuleType[_moduleType]; allModules = new address[](numOfModules); for (uint256 i = 0; i < numOfModules; i += 1) { bytes32 moduleId = keccak256(abi.encodePacked(i, _moduleType)); allModules[i] = modules[moduleId]; } } /// @dev Returns the forwarder address stored on the contract. function getForwarder() public view returns (address) { if (_forwarder == address(0)) { return Registry(registry).forwarder(); } return _forwarder; } /// @dev Lets a protocol admin withdraw tokens from this contract. function withdrawFunds(address to, address currency) external onlyProtocolAdmin { Registry _registry = Registry(registry); IERC20 _currency = IERC20(currency); address registryTreasury = _registry.treasury(); uint256 amount; bool isNativeToken = _isNativeToken(address(_currency)); if (isNativeToken) { amount = address(this).balance; } else { amount = _currency.balanceOf(address(this)); } uint256 registryTreasuryFee = (amount * _registry.getFeeBps(address(this))) / MAX_BPS; amount -= registryTreasuryFee; bool transferSuccess; if (isNativeToken) { (transferSuccess, ) = payable(to).call{ value: amount }(""); require(transferSuccess, "failed to withdraw funds"); (transferSuccess, ) = payable(registryTreasury).call{ value: registryTreasuryFee }(""); require(transferSuccess, "failed to withdraw funds to registry"); emit FundsWithdrawn(to, currency, amount, registryTreasuryFee); } else { transferSuccess = _currency.transfer(to, amount); require(transferSuccess, "failed to transfer payment"); transferSuccess = _currency.transfer(registryTreasury, registryTreasuryFee); require(transferSuccess, "failed to transfer payment to registry"); emit FundsWithdrawn(to, currency, amount, registryTreasuryFee); } } /// @dev Checks whether an address is to be interpreted as the native token function _isNativeToken(address _toCheck) internal pure returns (bool) { return _toCheck == NATIVE_TOKEN || _toCheck == address(0); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (metatx/ERC2771Context.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Context variant with ERC2771 support. */ abstract contract ERC2771Context is Context { address private _trustedForwarder; constructor(address trustedForwarder) { _trustedForwarder = trustedForwarder; } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == _trustedForwarder; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Multicall.sol) pragma solidity ^0.8.0; import "./Address.sol"; /** * @dev Provides a function to batch together multiple calls in a single external call. * * _Available since v4.1._ */ abstract contract Multicall { /** * @dev Receives and executes a batch of function calls on this contract. */ function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = Address.functionDelegateCall(address(this), data[i]); } return results; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IWETH { function deposit() external payable; function withdraw(uint256 amount) external; function transfer(address to, uint256 value) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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; 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"); (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"); (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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // CREATE2 -- contract deployment. import "@openzeppelin/contracts/utils/Create2.sol"; // Access Control import "@openzeppelin/contracts/access/Ownable.sol"; // Protocol Components import { IControlDeployer } from "./interfaces/IControlDeployer.sol"; import { Forwarder } from "./Forwarder.sol"; import { ProtocolControl } from "./ProtocolControl.sol"; contract Registry is Ownable { uint256 public constant MAX_PROVIDER_FEE_BPS = 1000; // 10% uint256 public defaultFeeBps = 500; // 5% /// @dev service provider / admin treasury address public treasury; /// @dev `Forwarder` for meta-transacitons address public forwarder; /// @dev The Create2 `ProtocolControl` contract factory. IControlDeployer public deployer; struct ProtocolControls { // E.g. if `latestVersion == 2`, there are 2 `ProtocolControl` contracts deployed. uint256 latestVersion; // Mapping from version => contract address. mapping(uint256 => address) protocolControlAddress; } /// @dev Mapping from app deployer => versions + app addresses. mapping(address => ProtocolControls) private _protocolControls; /// @dev Mapping from app (protocol control) => protocol provider fees for the app. mapping(address => uint256) private protocolControlFeeBps; /// @dev Emitted when the treasury is updated. event TreasuryUpdated(address newTreasury); /// @dev Emitted when a new deployer is set. event DeployerUpdated(address newDeployer); /// @dev Emitted when the default protocol provider fees bps is updated. event DefaultFeeBpsUpdated(uint256 defaultFeeBps); /// @dev Emitted when the protocol provider fees bps for a particular `ProtocolControl` is updated. event ProtocolControlFeeBpsUpdated(address indexed control, uint256 feeBps); /// @dev Emitted when an instance of `ProtocolControl` is migrated to this registry. event MigratedProtocolControl(address indexed deployer, uint256 indexed version, address indexed controlAddress); /// @dev Emitted when an instance of `ProtocolControl` is deployed. event NewProtocolControl( address indexed deployer, uint256 indexed version, address indexed controlAddress, address controlDeployer ); constructor( address _treasury, address _forwarder, address _deployer ) { treasury = _treasury; forwarder = _forwarder; deployer = IControlDeployer(_deployer); } /// @dev Deploys `ProtocolControl` with `_msgSender()` as admin. function deployProtocol(string memory uri) external { // Get deployer address caller = _msgSender(); // Get version for deployment uint256 version = getNextVersion(caller); // Deploy contract and get deployment address. address controlAddress = deployer.deployControl(version, caller, uri); _protocolControls[caller].protocolControlAddress[version] = controlAddress; emit NewProtocolControl(caller, version, controlAddress, address(deployer)); } /// @dev Returns the latest version of protocol control. function getProtocolControlCount(address _deployer) external view returns (uint256) { return _protocolControls[_deployer].latestVersion; } /// @dev Returns the protocol control address for the given version. function getProtocolControl(address _deployer, uint256 index) external view returns (address) { return _protocolControls[_deployer].protocolControlAddress[index]; } /// @dev Lets the owner migrate `ProtocolControl` instances from a previous registry. function addProtocolControl(address _deployer, address _protocolControl) external onlyOwner { // Get version for protocolControl uint256 version = getNextVersion(_deployer); _protocolControls[_deployer].protocolControlAddress[version] = _protocolControl; emit MigratedProtocolControl(_deployer, version, _protocolControl); } /// @dev Sets a new `ProtocolControl` deployer in case `ProtocolControl` is upgraded. function setDeployer(address _newDeployer) external onlyOwner { deployer = IControlDeployer(_newDeployer); emit DeployerUpdated(_newDeployer); } /// @dev Sets a new protocol provider treasury address. function setTreasury(address _newTreasury) external onlyOwner { treasury = _newTreasury; emit TreasuryUpdated(_newTreasury); } /// @dev Sets a new `defaultFeeBps` for protocol provider fees. function setDefaultFeeBps(uint256 _newFeeBps) external onlyOwner { require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%"); defaultFeeBps = _newFeeBps; emit DefaultFeeBpsUpdated(_newFeeBps); } /// @dev Sets the protocol provider fee for a particular instance of `ProtocolControl`. function setProtocolControlFeeBps(address protocolControl, uint256 _newFeeBps) external onlyOwner { require(_newFeeBps <= MAX_PROVIDER_FEE_BPS, "Registry: provider fee cannot be greater than 10%"); protocolControlFeeBps[protocolControl] = _newFeeBps; emit ProtocolControlFeeBpsUpdated(protocolControl, _newFeeBps); } /// @dev Returns the protocol provider fee for a particular instance of `ProtocolControl`. function getFeeBps(address protocolControl) external view returns (uint256) { uint256 fees = protocolControlFeeBps[protocolControl]; if (fees == 0) { return defaultFeeBps; } return fees; } /// @dev Returns the next version of `ProtocolControl` for the given `_deployer`. function getNextVersion(address _deployer) internal returns (uint256) { // Increment version _protocolControls[_deployer].latestVersion += 1; return _protocolControls[_deployer].latestVersion; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // Base import "./openzeppelin-presets/finance/PaymentSplitter.sol"; // Meta transactions import "@openzeppelin/contracts/metatx/ERC2771Context.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import { Registry } from "./Registry.sol"; import { ProtocolControl } from "./ProtocolControl.sol"; /** * Royalty automatically adds protocol provider (the registry) of protocol control to the payees * and shares that represent the fees. */ contract Royalty is PaymentSplitter, AccessControlEnumerable, ERC2771Context, Multicall { /// @dev The protocol control center. ProtocolControl private controlCenter; /// @dev Contract level metadata. string private _contractURI; modifier onlyModuleAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "only module admin role"); _; } /// @dev shares_ are scaled by 10,000 to prevent precision loss when including fees constructor( address payable _controlCenter, address _trustedForwarder, string memory _uri, address[] memory payees, uint256[] memory shares_ ) PaymentSplitter() ERC2771Context(_trustedForwarder) { require(payees.length == shares_.length, "Royalty: unequal number of payees and shares provided."); require(payees.length > 0, "Royalty: no payees provided."); // Set contract metadata _contractURI = _uri; // Set the protocol's control center. controlCenter = ProtocolControl(_controlCenter); Registry registry = Registry(controlCenter.registry()); uint256 feeBps = registry.getFeeBps(_controlCenter); uint256 totalScaledShares = 0; uint256 totalScaledSharesMinusFee = 0; // Scaling the share, so we don't lose precision on division for (uint256 i = 0; i < payees.length; i++) { uint256 scaledShares = shares_[i] * 10000; totalScaledShares += scaledShares; uint256 feeFromScaledShares = (scaledShares * feeBps) / 10000; uint256 scaledSharesMinusFee = scaledShares - feeFromScaledShares; totalScaledSharesMinusFee += scaledSharesMinusFee; // WARNING: Do not call _addPayee outside of this constructor. _addPayee(payees[i], scaledSharesMinusFee); } // WARNING: Do not call _addPayee outside of this constructor. uint256 totalFeeShares = totalScaledShares - totalScaledSharesMinusFee; _addPayee(registry.treasury(), totalFeeShares); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /// @dev See ERC2771 function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) { return ERC2771Context._msgSender(); } /// @dev See ERC2771 function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) { return ERC2771Context._msgData(); } /// @dev Sets contract URI for the contract-level metadata of the contract. function setContractURI(string calldata _URI) external onlyModuleAdmin { _contractURI = _URI; } /// @dev Returns the URI for the contract-level metadata of the contract. function contractURI() public view returns (string memory) { return _contractURI; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Create2.sol) pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy( uint256 amount, bytes32 salt, bytes memory bytecode ) internal returns (address) { address addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress( bytes32 salt, bytes32 bytecodeHash, address deployer ) internal pure returns (address) { bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)); return address(uint160(uint256(_data))); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IControlDeployer { /// @dev Emitted when an instance of `ProtocolControl` is deployed. event DeployedControl(address indexed registry, address indexed deployer, address indexed control); /// @dev Deploys an instance of `ProtocolControl` function deployControl( uint256 nonce, address deployer, string memory uri ) external returns (address); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; /* * @dev Minimal forwarder for GSNv2 */ contract Forwarder is EIP712 { using ECDSA for bytes32; struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; } bytes32 private constant TYPEHASH = keccak256("ForwardRequest(address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data)"); mapping(address => uint256) private _nonces; constructor() EIP712("GSNv2 Forwarder", "0.0.1") {} function getNonce(address from) public view returns (uint256) { return _nonces[from]; } function verify(ForwardRequest calldata req, bytes calldata signature) public view returns (bool) { address signer = _hashTypedDataV4( keccak256(abi.encode(TYPEHASH, req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data))) ).recover(signature); return _nonces[req.from] == req.nonce && signer == req.from; } function execute(ForwardRequest calldata req, bytes calldata signature) public payable returns (bool, bytes memory) { require(verify(req, signature), "MinimalForwarder: signature does not match request"); _nonces[req.from] = req.nonce + 1; // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = req.to.call{ gas: req.gas, value: req.value }( abi.encodePacked(req.data, req.from) ); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert("Transaction reverted silently"); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } // Check gas: https://ronan.eth.link/blog/ethereum-gas-dangers/ assert(gasleft() > req.gas / 63); return (success, result); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * Changelog: * 1. Remove add payees and shares in the constructor, so inherited class is responsible for adding. * 2. Change _addPayee(...) visibility to internal. DANGEROUS: Make sure it is not called outside from constructor * initialization. * 3. Add distribute(...) to distribute all owed amount to all payees. * 4. Add payeeCount() view to returns the number of payees. */ /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor() payable {} /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Getter for getting the number of payee */ function payeeCount() public view returns (uint256) { return _payees.length; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev Release the owed amount of token to all of the payees. */ function distribute() public virtual { for (uint256 i = 0; i < _payees.length; i++) { release(payable(_payees[i])); } } /** * @dev Release owed amount of the `token` to all of the payees. */ function distribute(IERC20 token) public virtual { for (uint256 i = 0; i < _payees.length; i++) { release(token, _payees[i]); } } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) internal { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
@dev Returns the protocol provider fee for a particular instance of `ProtocolControl`.
function getFeeBps(address protocolControl) external view returns (uint256) { uint256 fees = protocolControlFeeBps[protocolControl]; if (fees == 0) { return defaultFeeBps; } return fees; }
1,189,444
[ 1, 1356, 326, 1771, 2893, 14036, 364, 279, 6826, 791, 434, 1375, 5752, 3367, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2812, 1340, 38, 1121, 12, 2867, 1771, 3367, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 1656, 281, 273, 1771, 3367, 14667, 38, 1121, 63, 8373, 3367, 15533, 203, 3639, 309, 261, 3030, 281, 422, 374, 13, 288, 203, 5411, 327, 805, 14667, 38, 1121, 31, 203, 3639, 289, 203, 3639, 327, 1656, 281, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x9772ED906cA24303E5C4651E665ADe66AfEe51dD/sources/contracts/rev/drop/DropERC721Open.sol
@dev Returns whether operator restriction can be set in the given execution context.
function _canSetOperatorRestriction() internal virtual override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } Miscellaneous
838,033
[ 1, 1356, 2856, 3726, 9318, 848, 506, 444, 316, 326, 864, 4588, 819, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4169, 694, 5592, 11670, 1435, 2713, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 28335, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 13491, 16584, 3855, 15522, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x34fD51BB53Ff37f18108e934Fe4190Cfe4C57eA2/sources/contracts/monstermint.sol
require(saleIsActive, "Sale must be active to mint monster"); If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
function giftmonster(address giftAddress, string calldata message) public onlyOwner { require((totalSupply()+1) <= MAX_monster, "Purchase would exceed max supply of monster"); require(saletoken.allowance(msg.sender, address(this)) >= monsterPrice, "This contract is not approved to spend your token" ); saletoken.approve(walletToRecieveToken, monsterPrice); saletoken.transferFrom(msg.sender, walletToRecieveToken, monsterPrice); uint mintIndex = totalSupply(); if (totalSupply() < MAX_monster) { super._safeMint(giftAddress, mintIndex+1); super._setTokenURI(mintIndex+1,message); emit minted(giftAddress, mintIndex+1, message); } if (startingIndexBlock == 0 && (totalSupply() == MAX_monster || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
8,382,215
[ 1, 6528, 12, 87, 5349, 2520, 3896, 16, 315, 30746, 1297, 506, 2695, 358, 312, 474, 6921, 8190, 8863, 971, 732, 15032, 1404, 444, 326, 5023, 770, 471, 333, 353, 3344, 404, 13, 326, 1142, 272, 5349, 429, 1147, 578, 576, 13, 326, 1122, 1147, 358, 506, 272, 1673, 1839, 326, 679, 434, 675, 17, 87, 5349, 16, 444, 326, 5023, 770, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 314, 2136, 2586, 8190, 12, 2867, 314, 2136, 1887, 16, 533, 745, 892, 883, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12443, 4963, 3088, 1283, 1435, 15, 21, 13, 1648, 4552, 67, 2586, 8190, 16, 315, 23164, 4102, 9943, 943, 14467, 434, 6921, 8190, 8863, 203, 3639, 2583, 12, 21982, 278, 969, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 6921, 8190, 5147, 16, 315, 2503, 6835, 353, 486, 20412, 358, 17571, 3433, 1147, 6, 11272, 203, 3639, 12814, 278, 969, 18, 12908, 537, 12, 19177, 774, 5650, 21271, 1345, 16, 6921, 8190, 5147, 1769, 203, 3639, 12814, 278, 969, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 9230, 774, 5650, 21271, 1345, 16, 6921, 8190, 5147, 1769, 203, 540, 203, 3639, 2254, 312, 474, 1016, 273, 2078, 3088, 1283, 5621, 203, 5411, 309, 261, 4963, 3088, 1283, 1435, 411, 4552, 67, 2586, 8190, 13, 288, 203, 7734, 2240, 6315, 4626, 49, 474, 12, 75, 2136, 1887, 16, 312, 474, 1016, 15, 21, 1769, 203, 7734, 2240, 6315, 542, 1345, 3098, 12, 81, 474, 1016, 15, 21, 16, 2150, 1769, 203, 7734, 3626, 312, 474, 329, 12, 75, 2136, 1887, 16, 312, 474, 1016, 15, 21, 16, 883, 1769, 203, 5411, 289, 203, 540, 203, 3639, 309, 261, 18526, 1016, 1768, 422, 374, 597, 261, 4963, 3088, 1283, 1435, 422, 4552, 67, 2586, 8190, 747, 1203, 18, 5508, 1545, 2438, 3412, 1013, 67, 17201, 3719, 288, 203, 5411, 5023, 1016, 1768, 273, 1203, 18, 2696, 31, 2 ]
pragma solidity ^0.5.0; import "../SafeMath.sol"; import "../IErc20Token.sol"; import "../NamedContract.sol"; import "./StakingStorageV2.sol"; import "./StakingEventV2.sol"; /// @title Staking Contract Version 2 contract StakingV2 is NamedContract, StakingStorageV2, StakingEventV2 { using SafeMath for uint256; constructor() public { setContractName('Swipe Staking'); } /******************** * STANDARD ACTIONS * ********************/ /** * @notice Gets the staked amount of the provided address. * * @return The staked amount */ function getStakedAmount(address staker) public view returns (uint256) { Checkpoint storage current = _stakedMap[staker][0]; return current.stakedAmount; } /** * @notice Gets the prior staked amount of the provided address, at the provided block number. * * @return The staked amount */ function getPriorStakedAmount(address staker, uint256 blockNumber) external view returns (uint256) { if (blockNumber == 0) { return getStakedAmount(staker); } Checkpoint storage current = _stakedMap[staker][0]; for (uint i = current.blockNumberOrCheckpointIndex; i > 0; i--) { Checkpoint storage checkpoint = _stakedMap[staker][i]; if (checkpoint.blockNumberOrCheckpointIndex <= blockNumber) { return checkpoint.stakedAmount; } } return 0; } /** * @notice Stakes the provided amount of SXP from the message sender into this wallet. * * @param amount The amount to stake */ function stake(uint256 amount) external { require( amount >= _minimumStakeAmount, "Too small amount" ); Checkpoint storage current = _stakedMap[msg.sender][0]; current.blockNumberOrCheckpointIndex = current.blockNumberOrCheckpointIndex.add(1); current.stakedAmount = current.stakedAmount.add(amount); _stakedMap[msg.sender][current.blockNumberOrCheckpointIndex] = Checkpoint({ blockNumberOrCheckpointIndex: block.number, stakedAmount: current.stakedAmount }); _totalStaked = _totalStaked.add(amount); emit Stake( msg.sender, amount ); require( IErc20Token(_sxpTokenAddress).transferFrom( msg.sender, address(this), amount ), "Stake failed" ); } /** * @notice Claims reward of the provided nonce. * * @param nonce The claim nonce uniquely identifying the authorization to claim */ function claim(uint256 nonce) external { uint256 amount = _approvedClaimMap[msg.sender][nonce]; require( amount > 0, "Invalid nonce" ); require( _rewardPoolAmount >= amount, "Insufficient reward pool" ); delete _approvedClaimMap[msg.sender][nonce]; _rewardPoolAmount = _rewardPoolAmount.sub(amount); emit Claim( msg.sender, amount, nonce ); require( IErc20Token(_sxpTokenAddress).transfer( msg.sender, amount ), "Claim failed" ); } /** * @notice Withdraws the provided amount of staked * * @param amount The amount to withdraw */ function withdraw(uint256 amount) external { require( getStakedAmount(msg.sender) >= amount, "Exceeded amount" ); Checkpoint storage current = _stakedMap[msg.sender][0]; current.blockNumberOrCheckpointIndex = current.blockNumberOrCheckpointIndex.add(1); current.stakedAmount = current.stakedAmount.sub(amount); _stakedMap[msg.sender][current.blockNumberOrCheckpointIndex] = Checkpoint({ blockNumberOrCheckpointIndex: block.number, stakedAmount: current.stakedAmount }); _totalStaked = _totalStaked.sub(amount); emit Withdraw( msg.sender, amount ); require( IErc20Token(_sxpTokenAddress).transfer( msg.sender, amount ), "Withdraw failed" ); } /***************** * ADMIN ACTIONS * *****************/ /** * @notice Initializes contract. * * @param guardian Guardian address * @param sxpTokenAddress SXP token address * @param rewardProvider The reward provider address */ function initialize( address guardian, address sxpTokenAddress, address rewardProvider ) external { require( !_initialized, "Contract has been already initialized" ); _guardian = guardian; _sxpTokenAddress = sxpTokenAddress; _rewardProvider = rewardProvider; _minimumStakeAmount = 1000 * (10**18); _rewardCycle = 1 days; _rewardAmount = 40000 * (10**18); _rewardPendingPeriod = 1 days; _rewardCycleTimestamp = block.timestamp; _initialized = true; emit Initialize( _guardian, _sxpTokenAddress, _rewardProvider, _minimumStakeAmount, _rewardCycle, _rewardAmount, _rewardPendingPeriod, _rewardCycleTimestamp ); } /** * @notice Authorizes the transfer of guardianship from guardian to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeGuardianship( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new guardian. */ function authorizeGuardianshipTransfer(address authorizedAddress) external { require( msg.sender == _guardian, "Only the guardian can authorize a new address to become guardian" ); _authorizedNewGuardian = authorizedAddress; emit GuardianshipTransferAuthorization(_authorizedNewGuardian); } /** * @notice Transfers guardianship of this contract to the _authorizedNewGuardian. */ function assumeGuardianship() external { require( msg.sender == _authorizedNewGuardian, "Only the authorized new guardian can accept guardianship" ); address oldValue = _guardian; _guardian = _authorizedNewGuardian; _authorizedNewGuardian = address(0); emit GuardianUpdate(oldValue, _guardian); } /** * @notice Updates the minimum stake amount. * * @param newMinimumStakeAmount The amount to be allowed as minimum to users */ function setMinimumStakeAmount(uint256 newMinimumStakeAmount) external { require( msg.sender == _guardian, "Only the guardian can set the minimum stake amount" ); require( newMinimumStakeAmount > 0, "Invalid amount" ); uint256 oldValue = _minimumStakeAmount; _minimumStakeAmount = newMinimumStakeAmount; emit MinimumStakeAmountUpdate(oldValue, _minimumStakeAmount); } /** * @notice Updates the Reward Provider address, the only address that can provide reward. * * @param newRewardProvider The address of the new Reward Provider */ function setRewardProvider(address newRewardProvider) external { require( msg.sender == _guardian, "Only the guardian can set the reward provider address" ); address oldValue = _rewardProvider; _rewardProvider = newRewardProvider; emit RewardProviderUpdate(oldValue, _rewardProvider); } /** * @notice Updates the reward policy. * * @param newRewardCycle New reward cycle * @param newRewardAmount New reward amount a cycle * @param newRewardPendingPeriod New reward pending period */ function setRewardPolicy(uint256 newRewardCycle, uint256 newRewardAmount, uint256 newRewardPendingPeriod) external { require( msg.sender == _guardian, "Only the guardian can set the reward policy" ); _prevRewardCycle = _rewardCycle; _prevRewardAmount = _rewardAmount; _prevRewardPendingPeriod = _rewardPendingPeriod; _prevRewardCycleTimestamp = _rewardCycleTimestamp; _rewardCycle = newRewardCycle; _rewardAmount = newRewardAmount; _rewardPendingPeriod = newRewardPendingPeriod; _rewardCycleTimestamp = block.timestamp; emit RewardPolicyUpdate( _prevRewardCycle, _prevRewardAmount, _prevRewardPendingPeriod, _prevRewardCycleTimestamp, _rewardCycle, _rewardAmount, _rewardPendingPeriod, _rewardCycleTimestamp ); } /** * @notice Deposits the provided amount into reward pool. * * @param amount The amount to deposit into reward pool */ function depositRewardPool(uint256 amount) external { require( msg.sender == _rewardProvider, "Only the reword provider can deposit" ); _rewardPoolAmount = _rewardPoolAmount.add(amount); emit DepositRewardPool( msg.sender, amount ); require( IErc20Token(_sxpTokenAddress).transferFrom( msg.sender, address(this), amount ), "Deposit reward pool failed" ); } /** * @notice Withdraws the provided amount from reward pool. * * @param amount The amount to withdraw from reward pool */ function withdrawRewardPool(uint256 amount) external { require( msg.sender == _rewardProvider, "Only the reword provider can withdraw" ); require( _rewardPoolAmount >= amount, "Exceeded amount" ); _rewardPoolAmount = _rewardPoolAmount.sub(amount); emit WithdrawRewardPool( msg.sender, amount ); require( IErc20Token(_sxpTokenAddress).transfer( msg.sender, amount ), "Withdraw failed" ); } /** * @notice Approves the provided address to claim the provided amount. * * @param toAddress The address can claim reward * @param amount The amount to claim */ function approveClaim(address toAddress, uint256 amount) external returns(uint256) { require( msg.sender == _rewardProvider, "Only the reword provider can approve" ); require( _rewardPoolAmount >= amount, "Insufficient reward pool" ); _claimNonce = _claimNonce.add(1); _approvedClaimMap[toAddress][_claimNonce] = amount; emit ApproveClaim( toAddress, amount, _claimNonce ); return _claimNonce; } /******************** * VALUE ACTIONS * ********************/ /** * @notice Does not accept ETH. */ function () external payable { revert(); } /** * @notice Transfers out any accidentally sent ERC20 tokens. * * @param tokenAddress ERC20 token address, must not SXP * @param amount The amount to transfer out * @param toAddress To address */ function transferOtherErc20Token(address tokenAddress, uint256 amount, address toAddress) external returns (bool) { require( msg.sender == _guardian, "Only the guardian can transfer out" ); require( tokenAddress != _sxpTokenAddress, "Can't transfer SXP token out" ); return IErc20Token(tokenAddress).transfer( toAddress, amount ); } }
* @notice Deposits the provided amount into reward pool. @param amount The amount to deposit into reward pool/
function depositRewardPool(uint256 amount) external { require( msg.sender == _rewardProvider, "Only the reword provider can deposit" ); _rewardPoolAmount = _rewardPoolAmount.add(amount); emit DepositRewardPool( msg.sender, amount ); require( IErc20Token(_sxpTokenAddress).transferFrom( msg.sender, address(this), amount ), "Deposit reward pool failed" ); }
971,628
[ 1, 758, 917, 1282, 326, 2112, 3844, 1368, 19890, 2845, 18, 225, 3844, 1021, 3844, 358, 443, 1724, 1368, 19890, 2845, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 17631, 1060, 2864, 12, 11890, 5034, 3844, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 389, 266, 2913, 2249, 16, 203, 5411, 315, 3386, 326, 283, 1095, 2893, 848, 443, 1724, 6, 203, 3639, 11272, 203, 203, 3639, 389, 266, 2913, 2864, 6275, 273, 389, 266, 2913, 2864, 6275, 18, 1289, 12, 8949, 1769, 203, 203, 3639, 3626, 4019, 538, 305, 17631, 1060, 2864, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 3844, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 10897, 1310, 3462, 1345, 24899, 87, 23829, 1345, 1887, 2934, 13866, 1265, 12, 203, 7734, 1234, 18, 15330, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 3844, 203, 5411, 262, 16, 203, 5411, 315, 758, 1724, 19890, 2845, 2535, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x0651Ab69495f79d78a473e170248C839Efa137dC/sources/MasterChef.sol
JJAMPPONG tokens created per block.
uint256 public jjppPerBlock;
8,119,639
[ 1, 46, 46, 2192, 6584, 7390, 2430, 2522, 1534, 1203, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 10684, 11858, 2173, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x8735735acC6ddD2C192a899727d0F8aE0f34660C/sources/contracts/multi-chains/RoninTrustedOrganization.sol
* @inheritdoc IRoninTrustedOrganization/
function getTrustedOrganizationAt(uint256 _idx) public view override returns (TrustedOrganization memory) { address _addr = _consensusList[_idx]; return TrustedOrganization( _addr, _governorList[_idx], _bridgeVoterList[_idx], _consensusWeight[_addr], _addedBlock[_addr] ); }
3,829,442
[ 1, 36, 10093, 15908, 265, 267, 16950, 8113, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 336, 16950, 8113, 861, 12, 11890, 5034, 389, 3465, 13, 1071, 1476, 3849, 1135, 261, 16950, 8113, 3778, 13, 288, 203, 565, 1758, 389, 4793, 273, 389, 29220, 682, 63, 67, 3465, 15533, 203, 565, 327, 203, 1377, 30645, 8113, 12, 203, 3639, 389, 4793, 16, 203, 3639, 389, 75, 1643, 29561, 682, 63, 67, 3465, 6487, 203, 3639, 389, 18337, 58, 20005, 682, 63, 67, 3465, 6487, 203, 3639, 389, 29220, 6544, 63, 67, 4793, 6487, 203, 3639, 389, 9665, 1768, 63, 67, 4793, 65, 203, 1377, 11272, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-08-11 */ // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; // Part: IBetaBank interface IBetaBank { /// @dev Returns the address of BToken of the given underlying token, or 0 if not exists. function bTokens(address _underlying) external view returns (address); /// @dev Returns the address of the underlying of the given BToken, or 0 if not exists. function underlyings(address _bToken) external view returns (address); /// @dev Returns the address of the oracle contract. function oracle() external view returns (address); /// @dev Returns the address of the config contract. function config() external view returns (address); /// @dev Returns the interest rate model smart contract. function interestModel() external view returns (address); /// @dev Returns the position's collateral token and AmToken. function getPositionTokens(address _owner, uint _pid) external view returns (address _collateral, address _bToken); /// @dev Returns the debt of the given position. Can't be view as it needs to call accrue. function fetchPositionDebt(address _owner, uint _pid) external returns (uint); /// @dev Returns the LTV of the given position. Can't be view as it needs to call accrue. function fetchPositionLTV(address _owner, uint _pid) external returns (uint); /// @dev Opens a new position in the Beta smart contract. function open( address _owner, address _underlying, address _collateral ) external returns (uint pid); /// @dev Borrows tokens on the given position. function borrow( address _owner, uint _pid, uint _amount ) external; /// @dev Repays tokens on the given position. function repay( address _owner, uint _pid, uint _amount ) external; /// @dev Puts more collateral to the given position. function put( address _owner, uint _pid, uint _amount ) external; /// @dev Takes some collateral out of the position. function take( address _owner, uint _pid, uint _amount ) external; /// @dev Liquidates the given position. function liquidate( address _owner, uint _pid, uint _amount ) external; } // Part: IBetaConfig interface IBetaConfig { /// @dev Returns the risk level for the given asset. function getRiskLevel(address token) external view returns (uint); /// @dev Returns the rate of interest collected to be distributed to the protocol reserve. function reserveRate() external view returns (uint); /// @dev Returns the beneficiary to receive a portion interest rate for the protocol. function reserveBeneficiary() external view returns (address); /// @dev Returns the ratio of which the given token consider for collateral value. function getCollFactor(address token) external view returns (uint); /// @dev Returns the max amount of collateral to accept globally. function getCollMaxAmount(address token) external view returns (uint); /// @dev Returns max ltv of collateral / debt to allow a new position. function getSafetyLTV(address token) external view returns (uint); /// @dev Returns max ltv of collateral / debt to liquidate a position of the given token. function getLiquidationLTV(address token) external view returns (uint); /// @dev Returns the bonus incentive reward factor for liquidators. function getKillBountyRate(address token) external view returns (uint); } // Part: IBetaInterestModel interface IBetaInterestModel { /// @dev Returns the initial interest rate per year (times 1e18). function initialRate() external view returns (uint); /// @dev Returns the next interest rate for the market. /// @param prevRate The current interest rate. /// @param totalAvailable The current available liquidity. /// @param totalLoan The current outstanding loan. /// @param timePast The time past since last interest rate rebase in seconds. function getNextInterestRate( uint prevRate, uint totalAvailable, uint totalLoan, uint timePast ) external view returns (uint); } // Part: IBetaOracle interface IBetaOracle { /// @dev Returns the given asset price in ETH (wei), multiplied by 2**112. /// @param token The token to query for asset price function getAssetETHPrice(address token) external returns (uint); /// @dev Returns the given asset value in ETH (wei) /// @param token The token to query for asset value /// @param amount The amount of token to query function getAssetETHValue(address token, uint amount) external returns (uint); /// @dev Returns the conversion from amount of from` to `to`. /// @param from The source token to convert. /// @param to The destination token to convert. /// @param amount The amount of token for conversion. function convert( address from, address to, uint amount ) external returns (uint); } // Part: OpenZeppelin/[email protected]/Address /** * @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; 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"); (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"); (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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // Part: OpenZeppelin/[email protected]/Counters /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // Part: OpenZeppelin/[email protected]/ECDSA /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); } else { revert("ECDSA: invalid signature length"); } } /** * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC20Permit /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // Part: OpenZeppelin/[email protected]/Initializable /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute. return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // Part: OpenZeppelin/[email protected]/ReentrancyGuard /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Part: OpenZeppelin/[email protected]/EIP712 /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // Part: OpenZeppelin/[email protected]/IERC20Metadata /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // Part: OpenZeppelin/[email protected]/Pausable /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: OpenZeppelin/[email protected]/ERC20 /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // Part: OpenZeppelin/[email protected]/ERC20Permit /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // Part: BToken contract BToken is ERC20Permit, ReentrancyGuard { using SafeERC20 for IERC20; event Accrue(uint interest); event Mint(address indexed caller, address indexed to, uint amount, uint credit); event Burn(address indexed caller, address indexed to, uint amount, uint credit); uint public constant MINIMUM_LIQUIDITY = 10**6; // minimum liquidity to be locked in the pool when first mint occurs address public immutable betaBank; // BetaBank address address public immutable underlying; // the underlying token uint public interestRate; // current interest rate uint public lastAccrueTime; // last interest accrual timestamp uint public totalLoanable; // total asset amount available to be borrowed uint public totalLoan; // total amount of loan uint public totalDebtShare; // total amount of debt share /// @dev Initializes the BToken contract. /// @param _betaBank BetaBank address. /// @param _underlying The underlying token address for the bToken. constructor(address _betaBank, address _underlying) ERC20Permit('B Token') ERC20('B Token', 'bTOKEN') { require(_betaBank != address(0), 'constructor/betabank-zero-address'); require(_underlying != address(0), 'constructor/underlying-zero-address'); betaBank = _betaBank; underlying = _underlying; interestRate = IBetaInterestModel(IBetaBank(_betaBank).interestModel()).initialRate(); lastAccrueTime = block.timestamp; } /// @dev Returns the name of the token. function name() public view override returns (string memory) { try IERC20Metadata(underlying).name() returns (string memory data) { return string(abi.encodePacked('B ', data)); } catch (bytes memory) { return ERC20.name(); } } /// @dev Returns the symbol of the token. function symbol() public view override returns (string memory) { try IERC20Metadata(underlying).symbol() returns (string memory data) { return string(abi.encodePacked('b', data)); } catch (bytes memory) { return ERC20.symbol(); } } /// @dev Returns the decimal places of the token. function decimals() public view override returns (uint8) { try IERC20Metadata(underlying).decimals() returns (uint8 data) { return data; } catch (bytes memory) { return ERC20.decimals(); } } /// @dev Accrues interest rate and adjusts the rate. Can be called by anyone at any time. function accrue() public { // 1. Check time past condition uint timePassed = block.timestamp - lastAccrueTime; if (timePassed == 0) return; lastAccrueTime = block.timestamp; // 2. Check bank pause condition require(!Pausable(betaBank).paused(), 'BetaBank/paused'); // 3. Compute the accrued interest value over the past time (uint totalLoan_, uint totalLoanable_, uint interestRate_) = ( totalLoan, totalLoanable, interestRate ); // gas saving by avoiding multiple SLOADs IBetaConfig config = IBetaConfig(IBetaBank(betaBank).config()); IBetaInterestModel model = IBetaInterestModel(IBetaBank(betaBank).interestModel()); uint interest = (interestRate_ * totalLoan_ * timePassed) / (365 days) / 1e18; // 4. Update total loan and next interest rate totalLoan_ += interest; totalLoan = totalLoan_; interestRate = model.getNextInterestRate(interestRate_, totalLoanable_, totalLoan_, timePassed); // 5. Send a portion of collected interest to the beneficiary if (interest > 0) { uint reserveRate = config.reserveRate(); if (reserveRate > 0) { uint toReserve = (interest * reserveRate) / 1e18; _mint( config.reserveBeneficiary(), (toReserve * totalSupply()) / (totalLoan_ + totalLoanable_ - toReserve) ); } emit Accrue(interest); } } /// @dev Returns the debt value for the given debt share. Automatically calls accrue. function fetchDebtShareValue(uint _debtShare) external returns (uint) { accrue(); if (_debtShare == 0) { return 0; } return Math.ceilDiv(_debtShare * totalLoan, totalDebtShare); // round up } /// @dev Mints new bToken to the given address. /// @param _to The address to mint new bToken for. /// @param _amount The amount of underlying tokens to deposit via `transferFrom`. /// @return credit The amount of bToken minted. function mint(address _to, uint _amount) external nonReentrant returns (uint credit) { accrue(); uint amount; { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount); uint balAfter = IERC20(underlying).balanceOf(address(this)); amount = balAfter - balBefore; } uint supply = totalSupply(); if (supply == 0) { credit = amount - MINIMUM_LIQUIDITY; // Permanently lock the first MINIMUM_LIQUIDITY tokens totalLoanable += credit; totalLoan += MINIMUM_LIQUIDITY; totalDebtShare += MINIMUM_LIQUIDITY; _mint(address(1), MINIMUM_LIQUIDITY); // OpenZeppelin ERC20 does not allow minting to 0 } else { credit = (amount * supply) / (totalLoanable + totalLoan); totalLoanable += amount; } require(credit > 0, 'mint/no-credit-minted'); _mint(_to, credit); emit Mint(msg.sender, _to, _amount, credit); } /// @dev Burns the given bToken for the proportional amount of underlying tokens. /// @param _to The address to send the underlying tokens to. /// @param _credit The amount of bToken to burn. /// @return amount The amount of underlying tokens getting transferred out. function burn(address _to, uint _credit) external nonReentrant returns (uint amount) { accrue(); uint supply = totalSupply(); amount = (_credit * (totalLoanable + totalLoan)) / supply; require(amount > 0, 'burn/no-amount-returned'); totalLoanable -= amount; _burn(msg.sender, _credit); IERC20(underlying).safeTransfer(_to, amount); emit Burn(msg.sender, _to, amount, _credit); } /// @dev Borrows the funds for the given address. Must only be called by BetaBank. /// @param _to The address to borrow the funds for. /// @param _amount The amount to borrow. /// @return debtShare The amount of new debt share minted. function borrow(address _to, uint _amount) external nonReentrant returns (uint debtShare) { require(msg.sender == betaBank, 'borrow/not-BetaBank'); accrue(); IERC20(underlying).safeTransfer(_to, _amount); debtShare = Math.ceilDiv(_amount * totalDebtShare, totalLoan); // round up totalLoanable -= _amount; totalLoan += _amount; totalDebtShare += debtShare; } /// @dev Repays the debt using funds from the given address. Must only be called by BetaBank. /// @param _from The address to drain the funds to repay. /// @param _amount The amount of funds to call via `transferFrom`. /// @return debtShare The amount of debt share repaid. function repay(address _from, uint _amount) external nonReentrant returns (uint debtShare) { require(msg.sender == betaBank, 'repay/not-BetaBank'); accrue(); uint amount; { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(_from, address(this), _amount); uint balAfter = IERC20(underlying).balanceOf(address(this)); amount = balAfter - balBefore; } require(amount <= totalLoan, 'repay/amount-too-high'); debtShare = (amount * totalDebtShare) / totalLoan; // round down totalLoanable += amount; totalLoan -= amount; totalDebtShare -= debtShare; require(totalDebtShare >= MINIMUM_LIQUIDITY, 'repay/too-low-sum-debt-share'); } /// @dev Recovers tokens in this contract. EMERGENCY ONLY. Full trust in BetaBank. /// @param _token The token to recover, can even be underlying so please be careful. /// @param _to The address to recover tokens to. /// @param _amount The amount of tokens to recover, or MAX_UINT256 if whole balance. function recover( address _token, address _to, uint _amount ) external nonReentrant { require(msg.sender == betaBank, 'recover/not-BetaBank'); if (_amount == type(uint).max) { _amount = IERC20(_token).balanceOf(address(this)); } IERC20(_token).safeTransfer(_to, _amount); } } // Part: BTokenDeployer contract BTokenDeployer { /// @dev Deploys a new BToken contract for the given underlying token. function deploy(address _underlying) external returns (address) { bytes32 salt = keccak256(abi.encode(msg.sender, _underlying)); return address(new BToken{salt: salt}(msg.sender, _underlying)); } /// @dev Returns the deterministic BToken address for the given BetaBank + underlying. function bTokenFor(address _betaBank, address _underlying) external view returns (address) { bytes memory args = abi.encode(_betaBank, _underlying); bytes32 code = keccak256(abi.encodePacked(type(BToken).creationCode, args)); bytes32 salt = keccak256(args); return address(uint160(uint(keccak256(abi.encodePacked(hex'ff', address(this), salt, code))))); } } // File: BetaBank.sol contract BetaBank is IBetaBank, Initializable, Pausable { using Address for address; using SafeERC20 for IERC20; event Create(address indexed underlying, address bToken); event Open(address indexed owner, uint indexed pid, address bToken, address collateral); event Borrow(address indexed owner, uint indexed pid, uint amount, uint share, address borrower); event Repay(address indexed owner, uint indexed pid, uint amount, uint share, address payer); event Put(address indexed owner, uint indexed pid, uint amount, address payer); event Take(address indexed owner, uint indexed pid, uint amount, address to); event Liquidate( address indexed owner, uint indexed pid, uint amount, uint share, uint reward, address caller ); event SelflessLiquidate( address indexed owner, uint indexed pid, uint amount, uint share, address caller ); event SetGovernor(address governor); event SetPendingGovernor(address pendingGovernor); event SetOracle(address oracle); event SetConfig(address config); event SetInterestModel(address interestModel); event SetRunnerWhitelist(address indexed runner, bool ok); event SetOwnerWhitelist(address indexed owner, bool ok); event SetAllowPublicCreate(bool ok); struct Position { uint32 blockBorrowPut; // safety check uint32 blockRepayTake; // safety check address bToken; address collateral; uint collateralSize; uint debtShare; } uint private unlocked; // reentrancy variable address public deployer; // deployer address address public override oracle; // oracle address address public override config; // config address address public override interestModel; // interest rate model address address public governor; // current governor address public pendingGovernor; // pending governor bool public allowPublicCreate; // allow public to create pool status mapping(address => address) public override bTokens; // mapping from underlying to bToken mapping(address => address) public override underlyings; // mapping from bToken to underlying token mapping(address => bool) public runnerWhitelists; // whitelist of authorized routers mapping(address => bool) public ownerWhitelists; // whitelist of authorized owners mapping(address => mapping(uint => Position)) public positions; // mapping from user to the user's position id to Position info mapping(address => uint) public nextPositionIds; // mapping from user to next position id (position count) mapping(address => uint) public totalCollaterals; // mapping from token address to amount of collateral /// @dev Reentrancy guard modifier modifier lock() { require(unlocked == 1, 'BetaBank/locked'); unlocked = 2; _; unlocked = 1; } /// @dev Only governor is allowed modifier. modifier onlyGov() { require(msg.sender == governor, 'BetaBank/onlyGov'); _; } /// @dev Check if sender is allowed to perform action on behalf of the owner modifier. modifier isPermittedByOwner(address _owner) { require(isPermittedCaller(_owner, msg.sender), 'BetaBank/isPermittedByOwner'); _; } /// @dev Check is pool id exist for the owner modifier. modifier checkPID(address _owner, uint _pid) { require(_pid < nextPositionIds[_owner], 'BetaBank/checkPID'); _; } /// @dev Initializes this smart contract. No constructor to make this upgradable. function initialize( address _governor, address _deployer, address _oracle, address _config, address _interestModel ) external initializer { require(_governor != address(0), 'initialize/governor-zero-address'); require(_deployer != address(0), 'initialize/deployer-zero-address'); require(_oracle != address(0), 'initialize/oracle-zero-address'); require(_config != address(0), 'initialize/config-zero-address'); require(_interestModel != address(0), 'initialize/interest-model-zero-address'); governor = _governor; deployer = _deployer; oracle = _oracle; config = _config; interestModel = _interestModel; unlocked = 1; emit SetGovernor(_governor); emit SetOracle(_oracle); emit SetConfig(_config); emit SetInterestModel(_interestModel); } /// @dev Sets the next governor, which will be in effect when they accept. /// @param _pendingGovernor The next governor address. function setPendingGovernor(address _pendingGovernor) external onlyGov { pendingGovernor = _pendingGovernor; emit SetPendingGovernor(_pendingGovernor); } /// @dev Accepts to become the next governor. Must only be called by the pending governor. function acceptGovernor() external { require(msg.sender == pendingGovernor, 'acceptGovernor/not-pending-governor'); pendingGovernor = address(0); governor = msg.sender; emit SetGovernor(msg.sender); } /// @dev Updates the oracle address. Must only be called by the governor. function setOracle(address _oracle) external onlyGov { require(_oracle != address(0), 'setOracle/zero-address'); oracle = _oracle; emit SetOracle(_oracle); } /// @dev Updates the config address. Must only be called by the governor. function setConfig(address _config) external onlyGov { require(_config != address(0), 'setConfig/zero-address'); config = _config; emit SetConfig(_config); } /// @dev Updates the interest model address. Must only be called by the governor. function setInterestModel(address _interestModel) external onlyGov { require(_interestModel != address(0), 'setInterestModel/zero-address'); interestModel = _interestModel; emit SetInterestModel(_interestModel); } /// @dev Sets the whitelist statuses for the given runners. Must only be called by the governor. function setRunnerWhitelists(address[] calldata _runners, bool ok) external onlyGov { for (uint idx = 0; idx < _runners.length; idx++) { runnerWhitelists[_runners[idx]] = ok; emit SetRunnerWhitelist(_runners[idx], ok); } } /// @dev Sets the whitelist statuses for the given owners. Must only be called by the governor. function setOwnerWhitelists(address[] calldata _owners, bool ok) external onlyGov { for (uint idx = 0; idx < _owners.length; idx++) { ownerWhitelists[_owners[idx]] = ok; emit SetOwnerWhitelist(_owners[idx], ok); } } /// @dev Pauses and stops money market-related interactions. Must only be called by the governor. function pause() external whenNotPaused onlyGov { _pause(); } /// @dev Unpauses and allows again money market-related interactions. Must only be called by the governor. function unpause() external whenPaused onlyGov { _unpause(); } /// @dev Sets whether anyone can create btoken of any token. Must only be called by the governor. function setAllowPublicCreate(bool _ok) external onlyGov { allowPublicCreate = _ok; emit SetAllowPublicCreate(_ok); } /// @dev Creates a new money market for the given underlying token. Permissionless. /// @param _underlying The ERC-20 that is borrowable in the newly created market contract. function create(address _underlying) external lock whenNotPaused returns (address bToken) { require(allowPublicCreate || msg.sender == governor, 'create/unauthorized'); require(_underlying != address(this), 'create/not-like-this'); require(_underlying.isContract(), 'create/underlying-not-contract'); require(bTokens[_underlying] == address(0), 'create/underlying-already-exists'); require(IBetaOracle(oracle).getAssetETHPrice(_underlying) > 0, 'create/no-price'); bToken = BTokenDeployer(deployer).deploy(_underlying); bTokens[_underlying] = bToken; underlyings[bToken] = _underlying; emit Create(_underlying, bToken); } /// @dev Returns whether the given sender is allowed to interact with a position of the owner. function isPermittedCaller(address _owner, address _sender) public view returns (bool) { // ONE OF THE TWO CONDITIONS MUST HOLD: // 1. allow if sender is owner and owner is whitelisted. // 2. allow if owner is origin tx sender (for extra safety) and sender is globally accepted. return ((_owner == _sender && ownerWhitelists[_owner]) || (_owner == tx.origin && runnerWhitelists[_sender])); } /// @dev Returns the position's collateral token and BToken. function getPositionTokens(address _owner, uint _pid) external view override checkPID(_owner, _pid) returns (address _collateral, address _bToken) { Position storage pos = positions[_owner][_pid]; _collateral = pos.collateral; _bToken = pos.bToken; } /// @dev Returns the debt of the given position. Can't be view as it needs to call accrue. function fetchPositionDebt(address _owner, uint _pid) external override checkPID(_owner, _pid) returns (uint) { Position storage pos = positions[_owner][_pid]; return BToken(pos.bToken).fetchDebtShareValue(pos.debtShare); } /// @dev Returns the LTV of the given position. Can't be view as it needs to call accrue. function fetchPositionLTV(address _owner, uint _pid) external override checkPID(_owner, _pid) returns (uint) { return _fetchPositionLTV(positions[_owner][_pid]); } /// @dev Opens a new position to borrow a specific token for a specific collateral. /// @param _owner The owner of the newly created position. Sender must be allowed to act for. /// @param _underlying The token that is allowed to be borrowed in this position. /// @param _collateral The token that is used as collateral in this position. function open( address _owner, address _underlying, address _collateral ) external override whenNotPaused isPermittedByOwner(_owner) returns (uint pid) { address bToken = bTokens[_underlying]; require(bToken != address(0), 'open/bad-underlying'); require(_underlying != _collateral, 'open/self-collateral'); require(IBetaConfig(config).getCollFactor(_collateral) > 0, 'open/bad-collateral'); require(IBetaOracle(oracle).getAssetETHPrice(_collateral) > 0, 'open/no-price'); pid = nextPositionIds[_owner]++; Position storage pos = positions[_owner][pid]; pos.bToken = bToken; pos.collateral = _collateral; emit Open(_owner, pid, bToken, _collateral); } /// @dev Borrows tokens on the given position. Position must still be safe. /// @param _owner The position owner to borrow underlying tokens. /// @param _pid The position id to borrow underlying tokens. /// @param _amount The amount of underlying tokens to borrow. function borrow( address _owner, uint _pid, uint _amount ) external override lock whenNotPaused isPermittedByOwner(_owner) checkPID(_owner, _pid) { // 1. pre-conditions Position memory pos = positions[_owner][_pid]; require(pos.blockRepayTake != uint32(block.number), 'borrow/bad-block'); // 2. perform the borrow and update the position uint share = BToken(pos.bToken).borrow(msg.sender, _amount); pos.debtShare += share; positions[_owner][_pid].debtShare = pos.debtShare; positions[_owner][_pid].blockBorrowPut = uint32(block.number); // 3. make sure the position is still safe uint ltv = _fetchPositionLTV(pos); require(ltv <= IBetaConfig(config).getSafetyLTV(underlyings[pos.bToken]), 'borrow/not-safe'); emit Borrow(_owner, _pid, _amount, share, msg.sender); } /// @dev Repays tokens on the given position. Payer must be position owner or sender. /// @param _owner The position owner to repay underlying tokens. /// @param _pid The position id to repay underlying tokens. /// @param _amount The amount of underlying tokens to repay. function repay( address _owner, uint _pid, uint _amount ) external override lock whenNotPaused isPermittedByOwner(_owner) checkPID(_owner, _pid) { // 1. pre-conditions Position memory pos = positions[_owner][_pid]; require(pos.blockBorrowPut != uint32(block.number), 'repay/bad-block'); // 2. perform the repayment and update the position - no collateral check required uint share = BToken(pos.bToken).repay(msg.sender, _amount); pos.debtShare -= share; positions[_owner][_pid].debtShare = pos.debtShare; positions[_owner][_pid].blockRepayTake = uint32(block.number); emit Repay(_owner, _pid, _amount, share, msg.sender); } /// @dev Puts more collateral to the given position. Payer must be position owner or sender. /// @param _owner The position owner to put more collateral. /// @param _pid The position id to put more collateral. /// @param _amount The amount of collateral to put via `transferFrom`. function put( address _owner, uint _pid, uint _amount ) external override lock whenNotPaused isPermittedByOwner(_owner) checkPID(_owner, _pid) { // 1. pre-conditions Position memory pos = positions[_owner][_pid]; require(pos.blockRepayTake != uint32(block.number), 'put/bad-block'); // 2. transfer collateral tokens in uint amount; { uint balBefore = IERC20(pos.collateral).balanceOf(address(this)); IERC20(pos.collateral).safeTransferFrom(msg.sender, address(this), _amount); uint balAfter = IERC20(pos.collateral).balanceOf(address(this)); amount = balAfter - balBefore; } // 3. update the position and total collateral + check global collateral cap pos.collateralSize += amount; totalCollaterals[pos.collateral] += amount; require( totalCollaterals[pos.collateral] <= IBetaConfig(config).getCollMaxAmount(pos.collateral), 'put/too-much-collateral' ); positions[_owner][_pid].collateralSize = pos.collateralSize; positions[_owner][_pid].blockBorrowPut = uint32(block.number); emit Put(_owner, _pid, _amount, msg.sender); } /// @dev Takes some collateral out of the position and send it out. Position must still be safe. /// @param _owner The position owner to take collateral out. /// @param _pid The position id to take collateral out. /// @param _amount The amount of collateral to take via `transfer`. function take( address _owner, uint _pid, uint _amount ) external override lock whenNotPaused isPermittedByOwner(_owner) checkPID(_owner, _pid) { // 1. pre-conditions Position memory pos = positions[_owner][_pid]; require(pos.blockBorrowPut != uint32(block.number), 'take/bad-block'); // 2. update position collateral size and total collateral pos.collateralSize -= _amount; totalCollaterals[pos.collateral] -= _amount; positions[_owner][_pid].collateralSize = pos.collateralSize; positions[_owner][_pid].blockRepayTake = uint32(block.number); // 3. make sure the position is still safe uint ltv = _fetchPositionLTV(pos); require(ltv <= IBetaConfig(config).getSafetyLTV(underlyings[pos.bToken]), 'take/not-safe'); // 4. transfer collateral tokens out IERC20(pos.collateral).safeTransfer(msg.sender, _amount); emit Take(_owner, _pid, _amount, msg.sender); } /// @dev Liquidates the given position. Can be called by anyone but must be liquidatable. /// @param _owner The position owner to be liquidated. /// @param _pid The position id to be liquidated. /// @param _amount The amount of debt to be repaid by caller. Must not exceed half debt (rounded up). function liquidate( address _owner, uint _pid, uint _amount ) external override lock whenNotPaused checkPID(_owner, _pid) { // 1. check liquidation condition Position memory pos = positions[_owner][_pid]; address underlying = underlyings[pos.bToken]; uint ltv = _fetchPositionLTV(pos); require(ltv >= IBetaConfig(config).getLiquidationLTV(underlying), 'liquidate/not-liquidatable'); // 2. perform repayment uint debtShare = BToken(pos.bToken).repay(msg.sender, _amount); require(debtShare <= (pos.debtShare + 1) / 2, 'liquidate/too-much-liquidation'); // 3. calculate reward and payout uint debtValue = BToken(pos.bToken).fetchDebtShareValue(debtShare); uint collValue = IBetaOracle(oracle).convert(underlying, pos.collateral, debtValue); uint payout = Math.min( collValue + (collValue * IBetaConfig(config).getKillBountyRate(underlying)) / 1e18, pos.collateralSize ); // 4. update the position and total collateral pos.debtShare -= debtShare; positions[_owner][_pid].debtShare = pos.debtShare; pos.collateralSize -= payout; positions[_owner][_pid].collateralSize = pos.collateralSize; totalCollaterals[pos.collateral] -= payout; // 5. transfer the payout out IERC20(pos.collateral).safeTransfer(msg.sender, payout); emit Liquidate(_owner, _pid, _amount, debtShare, payout, msg.sender); } /// @dev onlyGov selfless liquidation if collateral size = 0 /// @param _owner The position owner to be liquidated. /// @param _pid The position id to be liquidated. /// @param _amount The amount of debt to be repaid by caller. function selflessLiquidate( address _owner, uint _pid, uint _amount ) external onlyGov lock checkPID(_owner, _pid) { // 1. check positions collateral size Position memory pos = positions[_owner][_pid]; require(pos.collateralSize == 0, 'selflessLiquidate/positive-collateral'); // 2. perform debt repayment uint debtValue = BToken(pos.bToken).fetchDebtShareValue(pos.debtShare); _amount = Math.min(_amount, debtValue); uint debtShare = BToken(pos.bToken).repay(msg.sender, _amount); pos.debtShare -= debtShare; positions[_owner][_pid].debtShare = pos.debtShare; emit SelflessLiquidate(_owner, _pid, _amount, debtShare, msg.sender); } /// @dev Recovers lost tokens by the governor. This function is extremely powerful so be careful. /// @param _bToken The BToken to propagate this recover call. /// @param _token The ERC20 token to recover. /// @param _amount The amount of tokens to recover. function recover( address _bToken, address _token, uint _amount ) external onlyGov lock { require(underlyings[_bToken] != address(0), 'recover/not-bToken'); BToken(_bToken).recover(_token, msg.sender, _amount); } /// @dev Returns the current LTV of the given position. function _fetchPositionLTV(Position memory pos) internal returns (uint) { if (pos.debtShare == 0) { return 0; // no debt means zero LTV } address oracle_ = oracle; // gas saving uint collFactor = IBetaConfig(config).getCollFactor(pos.collateral); require(collFactor > 0, 'fetch/bad-collateral'); uint debtSize = BToken(pos.bToken).fetchDebtShareValue(pos.debtShare); uint debtValue = IBetaOracle(oracle_).getAssetETHValue(underlyings[pos.bToken], debtSize); uint collCred = (pos.collateralSize * collFactor) / 1e18; uint collValue = IBetaOracle(oracle_).getAssetETHValue(pos.collateral, collCred); if (debtValue >= collValue) { return 1e18; // 100% LTV is very very bad and must always be liquidatable and unsafe } return (debtValue * 1e18) / collValue; } }
@dev Puts more collateral to the given position. Payer must be position owner or sender. @param _owner The position owner to put more collateral. @param _pid The position id to put more collateral. @param _amount The amount of collateral to put via `transferFrom`. 1. pre-conditions 2. transfer collateral tokens in
function put( address _owner, uint _pid, uint _amount ) external override lock whenNotPaused isPermittedByOwner(_owner) checkPID(_owner, _pid) { Position memory pos = positions[_owner][_pid]; require(pos.blockRepayTake != uint32(block.number), 'put/bad-block'); uint amount; { uint balBefore = IERC20(pos.collateral).balanceOf(address(this)); IERC20(pos.collateral).safeTransferFrom(msg.sender, address(this), _amount); uint balAfter = IERC20(pos.collateral).balanceOf(address(this)); amount = balAfter - balBefore; } totalCollaterals[pos.collateral] += amount; require( totalCollaterals[pos.collateral] <= IBetaConfig(config).getCollMaxAmount(pos.collateral), 'put/too-much-collateral' ); positions[_owner][_pid].collateralSize = pos.collateralSize; positions[_owner][_pid].blockBorrowPut = uint32(block.number); emit Put(_owner, _pid, _amount, msg.sender); }
10,721,897
[ 1, 26804, 1898, 4508, 2045, 287, 358, 326, 864, 1754, 18, 453, 1773, 1297, 506, 1754, 3410, 578, 5793, 18, 225, 389, 8443, 1021, 1754, 3410, 358, 1378, 1898, 4508, 2045, 287, 18, 225, 389, 6610, 1021, 1754, 612, 358, 1378, 1898, 4508, 2045, 287, 18, 225, 389, 8949, 1021, 3844, 434, 4508, 2045, 287, 358, 1378, 3970, 1375, 13866, 1265, 8338, 404, 18, 675, 17, 6381, 576, 18, 7412, 4508, 2045, 287, 2430, 316, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1378, 12, 203, 565, 1758, 389, 8443, 16, 203, 565, 2254, 389, 6610, 16, 203, 565, 2254, 389, 8949, 203, 225, 262, 3903, 3849, 2176, 1347, 1248, 28590, 353, 31465, 858, 5541, 24899, 8443, 13, 866, 16522, 24899, 8443, 16, 389, 6610, 13, 288, 203, 565, 11010, 3778, 949, 273, 6865, 63, 67, 8443, 6362, 67, 6610, 15533, 203, 565, 2583, 12, 917, 18, 2629, 426, 10239, 13391, 480, 2254, 1578, 12, 2629, 18, 2696, 3631, 296, 458, 19, 8759, 17, 2629, 8284, 203, 565, 2254, 3844, 31, 203, 565, 288, 203, 1377, 2254, 324, 287, 4649, 273, 467, 654, 39, 3462, 12, 917, 18, 12910, 2045, 287, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 1377, 467, 654, 39, 3462, 12, 917, 18, 12910, 2045, 287, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 1377, 2254, 324, 287, 4436, 273, 467, 654, 39, 3462, 12, 917, 18, 12910, 2045, 287, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 1377, 3844, 273, 324, 287, 4436, 300, 324, 287, 4649, 31, 203, 565, 289, 203, 565, 2078, 13535, 2045, 1031, 63, 917, 18, 12910, 2045, 287, 65, 1011, 3844, 31, 203, 565, 2583, 12, 203, 1377, 2078, 13535, 2045, 1031, 63, 917, 18, 12910, 2045, 287, 65, 1648, 23450, 1066, 809, 12, 1425, 2934, 588, 13535, 2747, 6275, 12, 917, 18, 12910, 2045, 287, 3631, 203, 1377, 296, 458, 19, 16431, 17, 81, 2648, 17, 12910, 2045, 287, 11, 203, 565, 11272, 2 ]
pragma solidity ^0.4.0; /** * Common utilities for trades */ contract TradeUtil { address internal owner; modifier isOwner(){ require(msg.sender == owner); _; } function getLength(uint[] data) internal pure returns(uint){ return data.length; } function findPositionInList(uint[] data, uint id) internal pure returns (uint){ uint _len = getLength(data); int _pos = -1; for(uint i=0; i<_len;i++){ if(id == data[i]){ _pos = int(i); break; } } require(_pos >= 0); return uint(_pos); } function maxNumber(uint[] data) internal pure returns(uint){ // require (data.length > 0); uint m = 0; if(data.length > 0){ m = data[0]; for(uint i = 1; i<data.length ; i++ ){ if(data[i] > m){ m = data[i]; } } } return m; } function countTransGreaterThan(uint[] v, uint tranid) internal pure returns(uint) { uint counter = 0; bool check = false; for (uint i = 0; i < v.length; i++) { if ( check == false && v[i] == tranid) { check = true; } if(check){ counter++; } } return counter; } function getSubListFromElementPosition(uint[] data, uint id) internal pure returns(uint[]){ uint _pos = findPositionInList(data, id); uint _len = getLength(data); uint _size = countTransGreaterThan(data, id); uint[] memory elements = new uint[](_size); for(uint i=_pos; i<_len;i++){ elements[i-_pos] = data[i]; } return elements; } function getSubListBySize(uint[] data, uint size) internal pure returns(uint[]){ uint _len = getLength(data); uint _start = _len - size; uint[] memory elements = new uint[](size); for(uint i=_start; i<_len;i++){ elements[i-_start] = data[i]; } return elements; } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function strToLower(string str) internal pure returns (string) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character... if ((bStr[i] >= 65) && (bStr[i] <= 90)) { // So we add 32 to make it lowercase bLower[i] = bytes1(int(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } } library TradeObjects { struct Position { uint id; string pKey; uint tranid; string account; string asset; string location; int quantity; int quantityPending; uint timestamp; string user; } struct Tran { uint tranid; string status; string account; string asset; string location; int quantity; int amount; uint timestamp; string user; } } contract PositionContract is TradeUtil { // event PositionUpdate(string account, string asset, string location); event PositionUpdate(uint id); // Holds actual trades mapping(uint => TradeObjects.Position) public positions; // Map of keys to ids mapping(string => uint) internal idMap; // List of ids uint[] public pos; // ============== function compileKey(string _account, string _asset, string _loaction) public pure returns (string){ string memory key = strConcat( _account, "_", _asset, "_", _loaction ); return strToLower(key); } // ============== /** * Check a position exists by key attributes */ function checkKeyExists(string _account, string _asset, string _loaction) public view returns(bool) { return checkKeyExists(compileKey(_account, _asset, _loaction)); } /** * Check a position exists by key */ function checkKeyExists(string _key) public view returns(bool) { return idMap[_key] > 0; } // ============== /** * Get ID based on key attributes of position */ function getKeyId(string _account, string _asset, string _loaction) public view returns(uint) { return idMap[compileKey(_account, _asset, _loaction)]; } /** * Get ID based on key of position */ function getKeyId(string _key) public view returns(uint) { return idMap[_key]; } // ============== /** * Get the position IDs */ function getPositionIds() public view returns (uint[]){ return pos; } // ============== /** * Update a position record */ function updatePosition( string _account, string _asset, string _loaction, int _quantity, int _quantityP, string _user ) public { string memory _key = compileKey(_account, _asset, _loaction); bool itemExists = checkKeyExists(_key); uint _id = 0; if(itemExists){ _id = idMap[_key]; } else { _id = maxNumber(pos) + 1; } TradeObjects.Position memory p = TradeObjects.Position(_id, _key, 0, _account, _asset, _loaction, _quantity, _quantityP, block.timestamp, _user); positions[_id] = p; idMap[_key] = _id; if(!itemExists){ pos.push(_id); } PositionUpdate(_id); } // ============== function getPosition(string _account, string _asset, string _loaction) public view returns ( uint id, string key, string account, string asset, string location, int quantity, int quantityPending, uint timestamp, string user ) { // uint _id = getId(_account, _asset, _loaction); uint _id = getKeyId(_account, _asset, _loaction); return getPosition(_id); } function getPosition(uint _id) public constant returns ( uint id, string key, string account, string asset, string location, int quantity, int quantityPending, uint timestamp, string user ){ // require(checkExists(_tranid)); TradeObjects.Position memory position = positions[_id]; id = position.id; key = position.pKey; account = position.account; asset = position.asset; location = position.location; quantity = position.quantity; quantityPending = position.quantityPending; timestamp = position.timestamp; user = position.user; } // ========== /** * Get the last few records */ function getSubListBySize(uint size) public view returns(uint[]) { return getSubListBySize(pos, size); } /** * Get all sebsequent records from a given position */ function getSubListFromElementPosition(uint id) public view returns(uint[]){ return getSubListFromElementPosition(pos, id); } /** * Get all subsequent records from a given key */ function getTransListFromKeyPosition(string key) public constant returns(uint[]){ uint _id = getKeyId(key); uint _pos = findPositionInList(pos, _id); return getSubListFromElementPosition(pos, _pos); } // ========== } contract TradeContract is TradeUtil { mapping(uint => TradeObjects.Tran) public transactions ; uint[] public trans; event TradeUpdate(uint tranid); event TradeStatusUpdate(uint tranid, string status); function getTransList() public constant returns(uint[]){ return trans; } function getTransListBySize(uint size) public constant returns(uint[]){ return getSubListBySize(trans, size); } function findTranPosition(uint tranid) public constant returns (uint){ return findPositionInList(trans, tranid); } function getTransListFromTranId(uint tranid) public constant returns(uint[]){ return getSubListFromElementPosition(trans, tranid); } function checkTranExists(uint _tranid) public constant returns (bool){ return (transactions[_tranid].tranid == _tranid); } function getTransLength() public constant returns(uint){ return trans.length; } function getTran(uint _tranid) public constant returns ( uint tranid, string status, string account, string asset, string location, int quantity, int amount, uint timestamp, string user ){ require(checkTranExists(_tranid)); TradeObjects.Tran memory tran = transactions[_tranid]; tranid = tran.tranid; status = tran.status; account = tran.account; asset = tran.asset; location = tran.location; quantity = tran.quantity; amount = tran.amount; timestamp = tran.timestamp; user = tran.user; } function updateTranStatus ( uint _tranid, string _status, string _user ) public { // Check that it exists require(checkTranExists(_tranid)); // Update transactions[_tranid].status = _status; transactions[_tranid].timestamp = block.timestamp; transactions[_tranid].user = _user; TradeStatusUpdate(_tranid, _status); } function updateTran( uint _tranid, string _status, string _account, string _asset, string _loaction, int _quantity, int _amount, string _user ) public { TradeObjects.Tran memory tran = TradeObjects.Tran(_tranid, _status, _account, _asset, _loaction, _quantity, _amount, block.timestamp, _user); bool itemExists = (transactions[_tranid].tranid == _tranid); transactions[_tranid] = tran; if(!itemExists){ trans.push(_tranid); } TradeUpdate(_tranid); } }
* Get all subsequent records from a given key/
function getTransListFromKeyPosition(string key) public constant returns(uint[]){ uint _id = getKeyId(key); uint _pos = findPositionInList(pos, _id); return getSubListFromElementPosition(pos, _pos); }
6,479,076
[ 1, 967, 777, 10815, 3853, 628, 279, 864, 498, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 1429, 682, 1265, 653, 2555, 12, 1080, 498, 13, 1071, 5381, 1135, 12, 11890, 63, 5717, 95, 203, 203, 3639, 2254, 389, 350, 273, 3579, 548, 12, 856, 1769, 203, 3639, 2254, 389, 917, 273, 1104, 2555, 24218, 12, 917, 16, 389, 350, 1769, 203, 3639, 327, 7040, 682, 1265, 1046, 2555, 12, 917, 16, 389, 917, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x42c39f5FE0E5f02F4Bd70D0F224103a2801cB8ec/sources/contracts/Battle.sol
Populate the CharacterProxy for player 2 Consume stamina for player 2 Collect 50% of the fee for the league rewards leagueRewards += msg.value / 2; Collect 50% of the fee for the feeCollector feeCollected += msg.value / 2;
function joinBattle(uint256 battleId, uint256 characterTokenId) external { require( characterContract.ownerOf(characterTokenId) == msg.sender, "Not the owner of the character" ); require( playerOngoingBattle[msg.sender] == 0, "Player already participating in another battle" ); BattleData storage battle = battles[battleId]; require( battle.battleStatus == BattleStatus.PENDING, "Battle has already started" ); require( battle.players[1] == address(0), "Battle already has two players" ); battle.characterIds[1] = characterTokenId; battle.players[1] = msg.sender; battle.battleStatus = BattleStatus.STARTED; playerOngoingBattle[msg.sender] = battleId; createCharacterProxies(characterTokenId, msg.sender, battleId); characterContract.consumeStamina(characterTokenId, staminaCost); emit NewBattle( battle.name, battleId, battle.players[0], msg.sender, characterTokenId ); }
5,669,695
[ 1, 19097, 326, 6577, 3886, 364, 7291, 576, 20418, 384, 301, 15314, 364, 7291, 576, 225, 9302, 6437, 9, 434, 326, 14036, 364, 326, 884, 20910, 283, 6397, 884, 20910, 17631, 14727, 1011, 1234, 18, 1132, 342, 576, 31, 225, 9302, 6437, 9, 434, 326, 14036, 364, 326, 14036, 7134, 14036, 10808, 329, 1011, 1234, 18, 1132, 342, 576, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1233, 38, 4558, 298, 12, 11890, 5034, 324, 4558, 298, 548, 16, 2254, 5034, 3351, 1345, 548, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 3351, 8924, 18, 8443, 951, 12, 11560, 1345, 548, 13, 422, 1234, 18, 15330, 16, 203, 5411, 315, 1248, 326, 3410, 434, 326, 3351, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 7291, 1398, 8162, 38, 4558, 298, 63, 3576, 18, 15330, 65, 422, 374, 16, 203, 5411, 315, 12148, 1818, 30891, 1776, 316, 4042, 324, 4558, 298, 6, 203, 3639, 11272, 203, 203, 3639, 605, 4558, 298, 751, 2502, 324, 4558, 298, 273, 324, 4558, 1040, 63, 70, 4558, 298, 548, 15533, 203, 3639, 2583, 12, 203, 5411, 324, 4558, 298, 18, 70, 4558, 298, 1482, 422, 605, 4558, 298, 1482, 18, 25691, 16, 203, 5411, 315, 38, 4558, 298, 711, 1818, 5746, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 324, 4558, 298, 18, 1601, 414, 63, 21, 65, 422, 1758, 12, 20, 3631, 203, 5411, 315, 38, 4558, 298, 1818, 711, 2795, 18115, 6, 203, 3639, 11272, 203, 203, 3639, 324, 4558, 298, 18, 11560, 2673, 63, 21, 65, 273, 3351, 1345, 548, 31, 203, 3639, 324, 4558, 298, 18, 1601, 414, 63, 21, 65, 273, 1234, 18, 15330, 31, 203, 3639, 324, 4558, 298, 18, 70, 4558, 298, 1482, 273, 605, 4558, 298, 1482, 18, 20943, 6404, 31, 203, 203, 3639, 7291, 1398, 8162, 38, 4558, 298, 63, 3576, 18, 15330, 65, 273, 324, 4558, 298, 548, 31, 2 ]
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/utils/Pausable.sol"; import "./CappedTokenSoldCrowdsaleHelper.sol"; import "./LaunchpadWhitelistCrowdsaleHelper.sol"; import "./HoldErc20TokenCrowdsaleHelper.sol"; import "./NoDeliveryCrowdsale.sol"; import "./TimedCrowdsaleHelper.sol"; import "./interfaces/ILaunchpadCrowdsale.sol"; /** * @title LaunchpadCrowdsale * @author Enjinstarter * @dev Launchpad crowdsale where there is no delivery of tokens in each purchase. */ contract LaunchpadCrowdsale is NoDeliveryCrowdsale, CappedTokenSoldCrowdsaleHelper, HoldErc20TokenCrowdsaleHelper, TimedCrowdsaleHelper, LaunchpadWhitelistCrowdsaleHelper, Pausable, ILaunchpadCrowdsale { using SafeMath for uint256; // https://github.com/crytic/slither/wiki/Detector-Documentation#too-many-digits // slither-disable-next-line too-many-digits address public constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD; struct LaunchpadCrowdsaleInfo { uint256 tokenCap; address whitelistContract; address tokenHold; uint256 minTokenHoldAmount; } address public governanceAccount; address public crowdsaleAdmin; // max 1 lot constructor( address wallet_, LaunchpadCrowdsaleInfo memory crowdsaleInfo, LotsInfo memory lotsInfo, Timeframe memory timeframe, PaymentTokenInfo[] memory paymentTokensInfo ) Crowdsale(wallet_, DEAD_ADDRESS, lotsInfo, paymentTokensInfo) CappedTokenSoldCrowdsaleHelper(crowdsaleInfo.tokenCap) HoldErc20TokenCrowdsaleHelper( crowdsaleInfo.tokenHold, crowdsaleInfo.minTokenHoldAmount ) TimedCrowdsaleHelper(timeframe) LaunchpadWhitelistCrowdsaleHelper(crowdsaleInfo.whitelistContract) { governanceAccount = msg.sender; crowdsaleAdmin = msg.sender; } modifier onlyBy(address account) { require( msg.sender == account, "LaunchpadCrowdsale: sender unauthorized" ); _; } /** * @return availableLots Available number of lots for beneficiary */ function getAvailableLotsFor(address beneficiary) external view override returns (uint256 availableLots) { if (!whitelisted(beneficiary)) { return 0; } availableLots = _getAvailableTokensFor(beneficiary).div( getBeneficiaryCap(beneficiary) ); } /** * @return remainingTokens Remaining number of tokens for crowdsale */ function getRemainingTokens() external view override returns (uint256 remainingTokens) { remainingTokens = tokenCap().sub(tokensSold); } function pause() external override onlyBy(crowdsaleAdmin) { _pause(); } function unpause() external override onlyBy(crowdsaleAdmin) { _unpause(); } function extendTime(uint256 newClosingTime) external override onlyBy(crowdsaleAdmin) { _extendTime(newClosingTime); } function setGovernanceAccount(address account) external override onlyBy(governanceAccount) { require(account != address(0), "LaunchpadCrowdsale: zero account"); governanceAccount = account; } function setCrowdsaleAdmin(address account) external override onlyBy(governanceAccount) { require(account != address(0), "LaunchpadCrowdsale: zero account"); crowdsaleAdmin = account; } /** * @param beneficiary Address receiving the tokens * @return lotSize_ lot size of token being sold */ function _lotSize(address beneficiary) internal view override returns (uint256 lotSize_) { lotSize_ = getBeneficiaryCap(beneficiary); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return tokenAmount Number of tokens that will be purchased */ function _getTokenAmount(uint256 lots, address beneficiary) internal view override returns (uint256 tokenAmount) { tokenAmount = lots.mul(_lotSize(beneficiary)); } /** * @param beneficiary Token beneficiary * @param paymentToken ERC20 payment token address * @param weiAmount Amount of wei contributed * @param tokenAmount Number of tokens to be purchased */ function _preValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view override whenNotPaused onlyWhileOpen tokenCapNotExceeded(tokensSold, tokenAmount) holdsSufficientTokens(beneficiary) isWhitelisted(beneficiary) { // TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded() if ( getTokensPurchasedBy(beneficiary).add(tokenAmount) > getBeneficiaryCap(beneficiary) ) { revert("LaunchpadCrowdsale: beneficiary cap exceeded"); } super._preValidatePurchase( beneficiary, paymentToken, weiAmount, tokenAmount ); } /** * @dev Extend parent behavior to update purchased amount of tokens by beneficiary. * @param beneficiary Token purchaser * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _updatePurchasingState( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal override { super._updatePurchasingState( beneficiary, paymentToken, weiAmount, tokenAmount ); _updateBeneficiaryTokensPurchased(beneficiary, tokenAmount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title CappedTokenSoldCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale with a limit for total tokens sold. */ contract CappedTokenSoldCrowdsaleHelper { using SafeMath for uint256; uint256 private _tokenCap; /** * @param tokenCap_ Max amount of tokens to be sold */ constructor(uint256 tokenCap_) { require(tokenCap_ > 0, "CappedTokenSoldHelper: zero cap"); _tokenCap = tokenCap_; } modifier tokenCapNotExceeded(uint256 tokensSold, uint256 tokenAmount) { require( tokensSold.add(tokenAmount) <= _tokenCap, "CappedTokenSoldHelper: cap exceeded" ); _; } /** * @return tokenCap_ the token cap of the crowdsale. */ function tokenCap() public view returns (uint256 tokenCap_) { tokenCap_ = _tokenCap; } /** * @dev Checks whether the token cap has been reached. * @return tokenCapReached_ Whether the token cap was reached */ function tokenCapReached(uint256 tokensSold) external view returns (bool tokenCapReached_) { tokenCapReached_ = (tokensSold >= _tokenCap); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/ILaunchpadWhitelist.sol"; /** * @title LaunchpadWhitelistCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale in which only whitelisted users can contribute. */ contract LaunchpadWhitelistCrowdsaleHelper { using SafeMath for uint256; address public whitelistContract; mapping(address => uint256) private _tokensPurchased; /** * @param whitelistContract_ whitelist contract address */ constructor(address whitelistContract_) { require( whitelistContract_ != address(0), "LaunchpadWhitelistCrowdsaleHelper: zero whitelist address" ); whitelistContract = whitelistContract_; } // TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded() /* modifier beneficiaryCapNotExceeded( address beneficiary, uint256 tokenAmount ) { require( _tokensPurchased[beneficiary].add(tokenAmount) <= ILaunchpadWhitelist(whitelistContract).whitelistedAmountFor( beneficiary ), "LaunchpadWhitelistCrowdsaleHelper: beneficiary cap exceeded" ); _; } */ modifier isWhitelisted(address account) { require( ILaunchpadWhitelist(whitelistContract).isWhitelisted(account), "LaunchpadWhitelistCrowdsaleHelper: account not whitelisted" ); _; } /** * @return tokenCap Cap for beneficiary in wei */ function getBeneficiaryCap(address beneficiary) public view returns (uint256 tokenCap) { require( beneficiary != address(0), "LaunchpadWhitelistCrowdsaleHelper: zero beneficiary address" ); tokenCap = ILaunchpadWhitelist(whitelistContract).whitelistedAmountFor( beneficiary ); } /** * @dev Returns the amount of tokens purchased so far by specific beneficiary. * @param beneficiary Address of contributor * @return tokensPurchased Tokens purchased by beneficiary so far in wei */ function getTokensPurchasedBy(address beneficiary) public view returns (uint256 tokensPurchased) { require( beneficiary != address(0), "LaunchpadWhitelistCrowdsaleHelper: zero beneficiary address" ); tokensPurchased = _tokensPurchased[beneficiary]; } function whitelisted(address account) public view returns (bool whitelisted_) { require( account != address(0), "LaunchpadWhitelistCrowdsaleHelper: zero account" ); whitelisted_ = ILaunchpadWhitelist(whitelistContract).isWhitelisted( account ); } /** * @param beneficiary Address of contributor * @param tokenAmount Amount in wei of token being purchased */ function _updateBeneficiaryTokensPurchased( address beneficiary, uint256 tokenAmount ) internal { _tokensPurchased[beneficiary] = _tokensPurchased[beneficiary].add( tokenAmount ); } /** * @return availableTokens Available number of tokens for purchase by beneficiary */ function _getAvailableTokensFor(address beneficiary) internal view returns (uint256 availableTokens) { availableTokens = getBeneficiaryCap(beneficiary).sub( getTokensPurchasedBy(beneficiary) ); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title HoldErc20TokenCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale where only wallets with specified amount of ERC20 token can contribute. */ contract HoldErc20TokenCrowdsaleHelper { using SafeERC20 for IERC20; address public tokenHoldContract; uint256 public minTokenHoldAmount; /** * @param tokenHoldContract_ ERC20 token contract address * @param minTokenHoldAmount_ minimum amount of token required to hold */ constructor(address tokenHoldContract_, uint256 minTokenHoldAmount_) { require( tokenHoldContract_ != address(0), "HoldErc20TokenCrowdsaleHelper: zero token hold address" ); require( minTokenHoldAmount_ > 0, "HoldErc20TokenCrowdsaleHelper: zero min token hold amount" ); tokenHoldContract = tokenHoldContract_; minTokenHoldAmount = minTokenHoldAmount_; } modifier holdsSufficientTokens(address account) { require( IERC20(tokenHoldContract).balanceOf(account) >= minTokenHoldAmount, "HoldErc20TokenCrowdsaleHelper: account hold less than min" ); _; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "./Crowdsale.sol"; /** * @title NoDeliveryCrowdsale * @author Enjinstarter * @dev Extension of Crowdsale contract where purchased tokens are not delivered. */ abstract contract NoDeliveryCrowdsale is Crowdsale { /** * @dev Overrides delivery by not delivering tokens upon purchase. */ function _deliverTokens(address, uint256) internal pure override { return; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title TimedCrowdsaleHelper * @author Enjinstarter * @dev Helper for crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsaleHelper { using SafeMath for uint256; struct Timeframe { uint256 openingTime; uint256 closingTime; } Timeframe private _timeframe; /** * Event for crowdsale extending * @param prevClosingTime old closing time * @param newClosingTime new closing time */ event TimedCrowdsaleExtended( uint256 prevClosingTime, uint256 newClosingTime ); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen() { require(isOpen(), "TimedCrowdsaleHelper: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param timeframe Crowdsale opening and closing times */ constructor(Timeframe memory timeframe) { require( timeframe.openingTime >= block.timestamp, "TimedCrowdsaleHelper: opening time is before current time" ); require( timeframe.closingTime > timeframe.openingTime, "TimedCrowdsaleHelper: closing time is before opening time" ); _timeframe.openingTime = timeframe.openingTime; _timeframe.closingTime = timeframe.closingTime; } /** * @return the crowdsale opening time. */ function openingTime() external view returns (uint256) { return _timeframe.openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _timeframe.closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { return block.timestamp >= _timeframe.openingTime && block.timestamp <= _timeframe.closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return block.timestamp > _timeframe.closingTime; } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code // slither-disable-next-line dead-code function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsaleHelper: already closed"); uint256 oldClosingTime = _timeframe.closingTime; require( newClosingTime > oldClosingTime, "TimedCrowdsaleHelper: before current closing time" ); _timeframe.closingTime = newClosingTime; emit TimedCrowdsaleExtended(oldClosingTime, newClosingTime); } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "./ICrowdsale.sol"; /** * @title ILaunchpadCrowdsale * @author Enjinstarter */ interface ILaunchpadCrowdsale is ICrowdsale { function getAvailableLotsFor(address beneficiary) external view returns (uint256 availableLots); function getRemainingTokens() external view returns (uint256 remainingTokens); function pause() external; function unpause() external; function extendTime(uint256 newClosingTime) external; function setGovernanceAccount(address account) external; function setCrowdsaleAdmin(address account) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; /** * @title ILaunchpadWhitelist * @author Enjinstarter */ interface ILaunchpadWhitelist { function addWhitelisted(address account, uint256 amount) external; function removeWhitelisted(address account) external; function addWhitelistedBatch( address[] memory accounts, uint256[] memory amounts ) external; function removeWhitelistedBatch(address[] memory accounts) external; function setGovernanceAccount(address account) external; function setWhitelistAdmin(address account) external; function isWhitelisted(address account) external view returns (bool isWhitelisted_); function whitelistedAmountFor(address account) external view returns (uint256 whitelistedAmount); event WhitelistedAdded(address indexed account, uint256 amount); event WhitelistedRemoved(address indexed account); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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.4._ */ 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.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; pragma abicoder v2; // solhint-disable-line import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./interfaces/ICrowdsale.sol"; /** * @title Crowdsale * @author Enjinstarter * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ERC20 tokens. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard, ICrowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_NUM_PAYMENT_TOKENS = 10; uint256 public constant TOKEN_MAX_DECIMALS = 18; uint256 public constant TOKEN_SELLING_SCALE = 10**TOKEN_MAX_DECIMALS; // Amount of tokens sold uint256 public tokensSold; // The token being sold // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address private _tokenSelling; // Lot size and maximum number of lots for token being sold LotsInfo private _lotsInfo; // Payment tokens // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names address[] private _paymentTokens; // Payment token decimals // https://github.com/crytic/slither/wiki/Detector-Documentation#variable-names-are-too-similar // slither-disable-next-line similar-names mapping(address => uint256) private _paymentDecimals; // Indicates whether ERC20 token is acceptable for payment mapping(address => bool) private _isPaymentTokens; // Address where funds are collected address private _wallet; // How many weis one token costs for each ERC20 payment token mapping(address => uint256) private _rates; // Amount of wei raised for each payment token mapping(address => uint256) private _weiRaised; /** * @dev Rates will denote how many weis one token costs for each ERC20 payment token. * For USDC or USDT payment token which has 6 decimals, minimum rate will * be 1000000000000 which will correspond to a price of USD0.000001 per token. * @param wallet_ Address where collected funds will be forwarded to * @param tokenSelling_ Address of the token being sold * @param lotsInfo Lot size and maximum number of lots for token being sold * @param paymentTokensInfo Addresses, decimals, rates and lot sizes of ERC20 tokens acceptable for payment */ constructor( address wallet_, address tokenSelling_, LotsInfo memory lotsInfo, PaymentTokenInfo[] memory paymentTokensInfo ) { require(wallet_ != address(0), "Crowdsale: zero wallet address"); require( tokenSelling_ != address(0), "Crowdsale: zero token selling address" ); require(lotsInfo.lotSize > 0, "Crowdsale: zero lot size"); require(lotsInfo.maxLots > 0, "Crowdsale: zero max lots"); require(paymentTokensInfo.length > 0, "Crowdsale: zero payment tokens"); require( paymentTokensInfo.length < MAX_NUM_PAYMENT_TOKENS, "Crowdsale: exceed max payment tokens" ); _wallet = wallet_; _tokenSelling = tokenSelling_; _lotsInfo = lotsInfo; for (uint256 i = 0; i < paymentTokensInfo.length; i++) { uint256 paymentDecimal = paymentTokensInfo[i].paymentDecimal; require( paymentDecimal <= TOKEN_MAX_DECIMALS, "Crowdsale: decimals exceed 18" ); address paymentToken = paymentTokensInfo[i].paymentToken; require( paymentToken != address(0), "Crowdsale: zero payment token address" ); uint256 rate_ = paymentTokensInfo[i].rate; require(rate_ > 0, "Crowdsale: zero rate"); _isPaymentTokens[paymentToken] = true; _paymentTokens.push(paymentToken); _paymentDecimals[paymentToken] = paymentDecimal; _rates[paymentToken] = rate_; } } /** * @return tokenSelling_ the token being sold */ function tokenSelling() external view override returns (address tokenSelling_) { tokenSelling_ = _tokenSelling; } /** * @return wallet_ the address where funds are collected */ function wallet() external view override returns (address wallet_) { wallet_ = _wallet; } /** * @return paymentTokens_ the payment tokens */ function paymentTokens() external view override returns (address[] memory paymentTokens_) { paymentTokens_ = _paymentTokens; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function rate(address paymentToken) external view override returns (uint256 rate_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); rate_ = _rate(paymentToken); } /** * @param beneficiary Address performing the token purchase * @return lotSize_ lot size of token being sold */ function lotSize(address beneficiary) public view override returns (uint256 lotSize_) { require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); lotSize_ = _lotSize(beneficiary); } /** * @return maxLots_ maximum number of lots for token being sold */ function maxLots() external view override returns (uint256 maxLots_) { maxLots_ = _lotsInfo.maxLots; } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function weiRaisedFor(address paymentToken) external view override returns (uint256 weiRaised_) { weiRaised_ = _weiRaisedFor(paymentToken); } /** * @param paymentToken ERC20 payment token address * @return isPaymentToken_ whether token is accepted for payment */ function isPaymentToken(address paymentToken) public view override returns (bool isPaymentToken_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); isPaymentToken_ = _isPaymentTokens[paymentToken]; } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return tokenAmount Number of tokens being sold that will be purchased */ function getTokenAmount(uint256 lots, address beneficiary) external view override returns (uint256 tokenAmount) { require(lots > 0, "Crowdsale: zero lots"); require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); tokenAmount = _getTokenAmount(lots, beneficiary); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return weiAmount Amount in wei of ERC20 payment token */ function getWeiAmount( address paymentToken, uint256 lots, address beneficiary ) external view override returns (uint256 weiAmount) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiAmount = _getWeiAmount(paymentToken, lots, beneficiary); } /** * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokens(address paymentToken, uint256 lots) external override { _buyTokensFor(msg.sender, paymentToken, lots); } /** * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) external override { _buyTokensFor(beneficiary, paymentToken, lots); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold */ function _buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) internal nonReentrant { require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: zero lots"); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); // calculate token amount to be created uint256 tokenAmount = _getTokenAmount(lots, beneficiary); // calculate wei amount to transfer to wallet uint256 weiAmount = _getWeiAmount(paymentToken, lots, beneficiary); _preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount); // update state _weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount); tokensSold = tokensSold.add(tokenAmount); _updatePurchasingState( beneficiary, paymentToken, weiAmount, tokenAmount ); emit TokensPurchased( msg.sender, beneficiary, paymentToken, lots, weiAmount, tokenAmount ); _processPurchase(beneficiary, tokenAmount); _forwardFunds(paymentToken, weiAmount); _postValidatePurchase( beneficiary, paymentToken, weiAmount, tokenAmount ); } /** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */ function _weiRaisedFor(address paymentToken) internal view virtual returns (uint256 weiRaised_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsale: payment token unaccepted" ); weiRaised_ = _weiRaised[paymentToken]; } /** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */ function _rate(address paymentToken) internal view virtual returns (uint256 rate_) { rate_ = _rates[paymentToken]; } /** * @return lotSize_ lot size of token being sold */ function _lotSize(address) internal view virtual returns (uint256 lotSize_) { lotSize_ = _lotsInfo.lotSize; } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _preValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo/rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _postValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code // slither-disable-next-line dead-code function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { IERC20(_tokenSelling).safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param paymentToken ERC20 payment token address * @param weiAmount Amount in wei of ERC20 payment token * @param tokenAmount Number of tokens to be purchased */ function _updatePurchasingState( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal virtual { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @return tokenAmount Number of tokens that will be purchased */ function _getTokenAmount(uint256 lots, address) internal view virtual returns (uint256 tokenAmount) { tokenAmount = lots.mul(_lotsInfo.lotSize).mul(TOKEN_SELLING_SCALE); } /** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return weiAmount Amount in wei of ERC20 payment token */ function _getWeiAmount( address paymentToken, uint256 lots, address beneficiary ) internal view virtual returns (uint256 weiAmount) { uint256 rate_ = _rate(paymentToken); uint256 tokenAmount = _getTokenAmount(lots, beneficiary); weiAmount = tokenAmount.mul(rate_).div(TOKEN_SELLING_SCALE); } /** * @dev Determines how ERC20 payment token is stored/forwarded on purchases. */ function _forwardFunds(address paymentToken, uint256 weiAmount) internal virtual { uint256 amount = weiAmount; if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) { uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub( _paymentDecimals[paymentToken] ); amount = weiAmount.div(10**decimalsDiff); } IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ICrowdsale * @author Enjinstarter */ interface ICrowdsale { struct LotsInfo { uint256 lotSize; uint256 maxLots; } struct PaymentTokenInfo { address paymentToken; uint256 paymentDecimal; uint256 rate; } function tokenSelling() external view returns (address tokenSelling_); function wallet() external view returns (address wallet_); function paymentTokens() external view returns (address[] memory paymentTokens_); function rate(address paymentToken) external view returns (uint256 rate_); function lotSize(address beneficiary) external view returns (uint256 lotSize_); function maxLots() external view returns (uint256 maxLots_); function weiRaisedFor(address paymentToken) external view returns (uint256 weiRaised_); function isPaymentToken(address paymentToken) external view returns (bool isPaymentToken_); function getTokenAmount(uint256 lots, address beneficiary) external view returns (uint256 tokenAmount); function getWeiAmount( address paymentToken, uint256 lots, address beneficiary ) external view returns (uint256 weiAmount); function buyTokens(address paymentToken, uint256 lots) external; function buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) external; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param paymentToken address of ERC20 token used for payment * @param lots number of lots to purchase * @param weiAmount weis paid for purchase * @param tokenAmount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, address indexed paymentToken, uint256 lots, uint256 weiAmount, uint256 tokenAmount ); }
* @dev Overrides delivery by not delivering tokens upon purchase./
function _deliverTokens(address, uint256) internal pure override { return; }
9,971,100
[ 1, 13084, 7912, 635, 486, 11795, 310, 2430, 12318, 23701, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 26672, 5157, 12, 2867, 16, 2254, 5034, 13, 2713, 16618, 3849, 288, 203, 3639, 327, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-09-23 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IONXFarm interface IONXFarm { // View function to see pending OnX on frontend. function pendingOnX(uint256 _pid, address _user) external view returns (uint256); // Deposit tokens to OnXFarmTest for OnX allocation. function deposit(uint256 _pid, uint256 _amount) external; // Withdraw tokens from OnXFarmTest function withdraw(uint256 _pid, uint256 _amount) external; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of OnX // entitled to a user but is pending to be distributed is: // // pending reward = (userInfo.amount * pool.accOnXPerShare) - userInfo.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accOnXPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each user that stakes tokens. // mapping(uint256 => mapping(address => UserInfo)) external userInfo; function userInfo(uint256 _pid, address _user) external view returns (UserInfo memory); } // Part: OpenZeppelin/[email protected]/Address /** * @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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: Uni interface Uni { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function withdrawalQueue(uint256 index) external view returns (address); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); function deposit(uint256 amount, address recipient, bool stakeInstantly) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function availableDepositLimit() external view returns (uint256); function avgAPY() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers function _onlyAuthorized() internal { require(msg.sender == strategist || msg.sender == governance()); } function _onlyEmergencyAuthorized() internal { require(msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management()); } function _onlyStrategist() internal { require(msg.sender == strategist); } function _onlyGovernance() internal { require(msg.sender == governance()); } function _onlyKeepers() internal { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management() ); } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); SafeERC20.safeApprove(want, _vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external { _onlyAuthorized(); require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external { _onlyAuthorized(); require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external { _onlyStrategist(); require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external { _onlyAuthorized(); minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external { _onlyAuthorized(); maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external { _onlyAuthorized(); profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external { _onlyAuthorized(); debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external { _onlyAuthorized(); metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external { _onlyKeepers(); // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external { _onlyKeepers(); uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) SafeERC20.safeTransfer(want, msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); SafeERC20.safeTransfer(want, _newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external { _onlyEmergencyAuthorized(); emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external { _onlyGovernance(); require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); SafeERC20.safeTransfer(IERC20(_token), governance(), IERC20(_token).balanceOf(address(this))); } } // File: StrategyONXankr.sol contract StrategyONXankr is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant onxFarm = address(0x168F8469Ac17dd39cd9a2c2eAD647f814a488ce9); uint256 public constant pid = 1; address public constant onx = address(0xE0aD1806Fd3E7edF6FF52Fdb822432e847411033); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant sushiswap = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); address public dex; constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want // maxReportDelay = 6300; // profitFactor = 100; // debtThreshold = 0; dex = uniswap; _approveDex(); } function _approveBasic() internal { want.approve(onxFarm, 0); want.approve(onxFarm, type(uint256).max); } function _approveDex() internal virtual { IERC20(onx).approve(dex, 0); IERC20(onx).approve(dex, type(uint256).max); IERC20(weth).approve(dex, 0); IERC20(weth).approve(dex, type(uint256).max); } function approveAll() external { _onlyAuthorized(); _approveBasic(); _approveDex(); } function switchDex(bool isUniswap) external { _onlyAuthorized(); if (isUniswap) dex = uniswap; else dex = sushiswap; _approveDex(); } function name() external view override returns (string memory) { return "StrategyONXankr"; } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { return IONXFarm(onxFarm).userInfo(pid, address(this)).amount; } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function pendingONXRewards() public view returns (uint256) { return IONXFarm(onxFarm).pendingOnX(pid, address(this)); } function claimONXRewards() internal { // Zero amount can trigger internal harvest in withdraw function to acquire ONX rewards IONXFarm(onxFarm).withdraw(pid, 0); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 before = balanceOfWant(); claimONXRewards(); // Route: ONX => WETH => want uint256 _onx = IERC20(onx).balanceOf(address(this)); if (_onx > 0) { address[] memory path = new address[](2); path[0] = onx; path[1] = weth; Uni(dex).swapExactTokensForTokens(_onx, uint256(0), path, address(this), now); } uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); Uni(dex).swapExactTokensForTokens(_weth, uint256(0), path, address(this), now); } _profit = want.balanceOf(address(this)).sub(before); uint _total = estimatedTotalAssets(); uint _debt = vault.strategies(address(this)).totalDebt; if(_total < _debt) { _loss = _debt - _total; _profit = 0; } if (_debtOutstanding > 0) { _withdrawSome(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, balanceOfWant().sub(_profit)); } } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) return; uint256 _want = want.balanceOf(address(this)); if (_want > 0) { IONXFarm(onxFarm).deposit(pid, _want); } } function _withdrawSome(uint256 _amount) internal returns (uint256) { _amount = Math.min(_amount, balanceOfPool()); uint _before = balanceOfWant(); IONXFarm(onxFarm).withdraw(pid, _amount); return balanceOfWant().sub(_before); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _balance = balanceOfWant(); if (_balance < _amountNeeded) { _liquidatedAmount = _withdrawSome(_amountNeeded.sub(_balance)); _liquidatedAmount = _liquidatedAmount.add(_balance); _loss = _amountNeeded.sub(_liquidatedAmount); // this should be 0. o/w there must be an error } else { _liquidatedAmount = _amountNeeded; } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { uint256 _loss = 0; (_amountFreed, _loss) = liquidatePosition(estimatedTotalAssets()); } function prepareMigration(address _newStrategy) internal override { IONXFarm(onxFarm).withdraw(pid, balanceOfPool()); _migrateRewards(_newStrategy); } function _migrateRewards(address _newStrategy) internal { IERC20(onx).safeTransfer(_newStrategy, IERC20(onx).balanceOf(address(this))); IERC20(weth).safeTransfer(_newStrategy, IERC20(weth).balanceOf(address(this))); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](4); protected[0] = onx; protected[1] = weth; return protected; } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view override returns (uint256) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); uint256[] memory amounts = Uni(dex).getAmountsOut(_amtInWei, path); return amounts[amounts.length - 1]; } }
* @notice Used to change `minReportDelay`. `minReportDelay` is the minimum number of blocks that should pass for `harvest()` to be called. For external keepers (such as the Keep3r network), this is the minimum time between jobs to wait. (see `harvestTrigger()` for more details.) This may only be called by governance or the strategist. @param _delay The minimum number of seconds to wait between harvests./
function setMinReportDelay(uint256 _delay) external { _onlyAuthorized(); minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); }
15,164,034
[ 1, 6668, 358, 2549, 1375, 1154, 4820, 6763, 8338, 1375, 1154, 4820, 6763, 68, 353, 326, 5224, 1300, 225, 434, 4398, 716, 1410, 1342, 364, 1375, 30250, 26923, 20338, 358, 506, 2566, 18, 225, 2457, 3903, 3455, 414, 261, 87, 2648, 487, 326, 10498, 23, 86, 2483, 3631, 333, 353, 326, 5224, 225, 813, 3086, 6550, 358, 2529, 18, 261, 5946, 1375, 30250, 26923, 6518, 20338, 225, 364, 1898, 3189, 12998, 225, 1220, 2026, 1338, 506, 2566, 635, 314, 1643, 82, 1359, 578, 326, 609, 1287, 376, 18, 225, 389, 10790, 1021, 5224, 1300, 434, 3974, 358, 2529, 3086, 17895, 90, 25563, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27724, 4820, 6763, 12, 11890, 5034, 389, 10790, 13, 3903, 288, 203, 3639, 389, 3700, 15341, 5621, 203, 3639, 1131, 4820, 6763, 273, 389, 10790, 31, 203, 3639, 3626, 19301, 2930, 4820, 6763, 24899, 10790, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-12 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } pragma solidity ^0.8.7; // Some hints to help with the math: // // https://mathopenref.com/graphfunctions.html // https://www.wolframalpha.com/input/?i2d=true&i=Integrate%5BPower%5Be%2Ckt%5D%2C%7Bt%2Ca%2Cb%7D%5D // https://www.wolframalpha.com/input/?i2d=true&i=plot+Piecewise%5B%7B%7BPower%5Be%2C4%5C%2840%29t-1%5C%2841%29%5D%2Ct%3C%3D1%7D%2C%7B1%2C1%3Ct%3C2%7D%2C%7BPower%5Be%2C-t%2B2%5D%2Ct%3E%3D2%7D%7D%5D%5C%2844%29+0.01%2BIntegrate%5BPiecewise%5B%7B%7BPower%5Be%2C4%5C%2840%29t-1%5C%2841%29%5D%2Ct%3C%3D1%7D%2C%7B1%2C1%3Ct%3C2%7D%2C%7BPower%5Be%2C-t%2B2%5D%2Ct%3E%3D2%7D%7D%5D%2Ct%5D+from+t%3D0+to+8 // // Special thanks to ABDK! // https://abdk.consulting // https://github.com/abdk-consulting // /** * @dev declare and safegaurd token allocations among a number of slices. */ library EmissionCurves { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; struct Curve { int128 timeStart; // time of emission start as 64.64 seconds int128 durationGrowth; // seconds until max emissions reached as 64.64 int128 expGrowth; // e^(expGrowth * t) t=[-durationGrowthI, 0) as +64.64 int128 durationMax; // seconds duration of max emissions as 64.64 int128 durationDecay; // seconds duration of emission decay phase as 64.64 int128 expDecay; // e^(expDecay * t) t=(0, durationDecayI] as -64.64 int128 A; // area under entire envelope in world units } function newCurve( uint256 timeStart, uint32 durationGrowth, uint8 expGrowth, uint32 durationMax, uint32 durationDecay, uint8 expDecay ) internal pure returns (Curve memory) { return newCurve64x64( timeStart.fromUInt(), uint256(durationGrowth).fromUInt(), uint256(expGrowth).fromUInt().div(uint256(10).fromUInt()), uint256(durationMax).fromUInt(), uint256(durationDecay).fromUInt(), uint256(expDecay).fromUInt().div(uint256(10).fromUInt())); } function newCurve64x64( int128 timeStart, int128 durationGrowth, int128 expGrowth, int128 durationMax, int128 durationDecay, int128 expDecay ) internal pure returns (Curve memory) { // It is easiest to treat the time of max emission as t=0 and growth phase // occuring before t=0 to avoid dealing with the asymptotic coming from -∞. // // area under growth era = ∫(-1, 0) e^(expGrowth * t) dt // = (1 - e^-expGrowth / expGrowth // int128 I_growth = expGrowth == 0 ? int128(0) : uint256(1).fromUInt().sub(expGrowth.neg().exp()).div(expGrowth); // After the growth phase, max emissions occur for the given duration. // // area under max emission era = ∫(0, 1) 1 dt // = 1 // //int128 I_max = 1; // After the max emission phase, emissions decay exponentially. // // area under decay era = ∫(0, 1) e^-(expDecay * t) dt // = (1 - e^-expDecay) / expDecay // int128 I_decay = expDecay == 0 ? int128(0) : uint256(1).fromUInt().sub(expDecay.neg().exp()).div(expDecay); return Curve( timeStart, durationGrowth, expGrowth, durationMax, durationDecay, expDecay, I_growth.mul(durationGrowth).add(durationMax).add(I_decay.mul(durationDecay)) ); } function calcGrowth(Curve storage curve, uint256 timestamp) public view returns (int128) { // time elapsed since curve start int128 t = timestamp.fromUInt().sub(curve.timeStart); if (t < 0) { return 0; } if (curve.durationGrowth == 0 && curve.durationMax == 0 && curve.durationDecay == 0) { // Since there's no envelope defined, minting may occur whenever, // so return the unit max and defer to total allocation limit. return uint256(1).fromUInt(); } if (t < curve.durationGrowth) { // convert time from world to integral coordinates to keep the math simple and no overflow t = t.div(curve.durationGrowth); return _integrateGrowth(curve, t) .mul(curve.durationGrowth) // scale to world coordinates .div(curve.A); // normalize against sum of all phases } t = t.sub(curve.durationGrowth); if (t < curve.durationMax) { return _integrateGrowth(curve, uint256(1).fromUInt()) // growth phase .mul(curve.durationGrowth) // in world coordinates .add(t) // add max emission area .div(curve.A); // normalize against sum of all phases } t = t.sub(curve.durationMax); if (t < curve.durationDecay) { // convert time from world to integral coordinates to keep the math simple and no overflow t = t.div(curve.durationDecay); return _integrateGrowth(curve, uint256(1).fromUInt()) // growth phase .mul(curve.durationGrowth) // scale to world coordinates .add(curve.durationMax) // max phase (already in world coords) .add(_integrateDecay(curve, t) // decay phase .mul(curve.durationDecay)) // scale to world coordinates .div(curve.A); // normalize against sum of all phases } // 100% return uint256(1).fromUInt(); } function _integrateGrowth(Curve storage curve, int128 t) private view returns (int128) { // // = ∫(-durationGrowthI, t-durationGrowthI) e^(expGrowth * T) dT // = (e^((t - durationGrowthI) * expGrowth) - e^(-durationGrowthI * expGrowth)) / expGrowth // return t .sub(uint256(1).fromUInt()) .mul(curve.expGrowth) .exp() .sub(curve.expGrowth.neg().exp()) .div(curve.expGrowth); } function _integrateDecay(Curve storage curve, int128 t) private view returns (int128) { // // = ∫(0,t) e^(-expDecay * T) dT // = (1 - e^(-expDecay * t)) / expDecay // return uint256(1).fromUInt() .sub(curve.expDecay.mul(t).neg().exp()) .div(curve.expDecay); } } // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 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"); (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"); (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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } /** * @dev Extension of ERC1155 to support Compound-like voting and delegation. This version is more generic than * Compound's, and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * Multiple ERC1155 token ids represent different voting classes each having a distinct voting power multiplier. * Token ID 0 should represent the most common share so that the vast majority of accounts do not need * to send transactions to change the default token. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. */ contract ERC20_1155Votes is ERC1155Supply, EIP712, IERC20Metadata, IERC20Permit { using Counters for Counters.Counter; uint256 private _n; // number of token ids (share classes) uint256 private _aggregateSupply; // aggregate supply summed over all token ids string private _name; string private _symbol; // _defaultToken stores each account's default token used for ERC20 approvals/transfers. // // Since the mapping returns 0 by default it is recommended that the most common token class // be represented as tokenId == 0. If tokenId 0 represents common shares, for example, then // this mapping will be sparsely filled. Most accounts would never call setDefaultToken // to change the default since they would only ever hold the common class/share. // mapping(address => uint256) _defaultToken; // Default token ID for ERC20 approvals/tansfers. struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; mapping(address => Counters.Counter) internal _nonces; // for ERC20 transfers only, not used for ERC1155 transfers mapping(address => mapping(address => uint256)) private _allowances; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Constructs a set of `n` tokens with varying voting weights determined by a power function. */ constructor(string memory name_, string memory symbol_, string memory uri_, uint256 n) ERC1155(uri_) EIP712(name_, "1") { _name = name_; _symbol = symbol_; _n = n; } function setDefaultToken(uint256 id) public { _defaultToken[msg.sender] = id; } function defaultToken() public view returns (uint256) { return _defaultToken[msg.sender]; } /** * @dev Returns the IERC20Metadata name of the token set. */ function name() external view override returns (string memory) { return _name; } /** * @dev Returns the IERC20Metadata base symbol of all tokens. */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev Returns the IERC20Metadata decimals places of the tokens. */ function decimals() external view override returns (uint8) { return 18; } /** * @dev Returns the aggregate total supply of all tokens regardless of token class. */ function totalSupply() public view override returns (uint256 supply) { for (uint id = 0; id < _n; ++id) { supply += totalSupply(id); } } /** * @dev Returns the aggregate number of tokens over all classes owned by `account`. */ function balanceOf(address account) public view override returns (uint256 balance) { for (uint id = 0; id < _n; ++id) { balance += balanceOf(account, id); } } /** * @dev Amount of `owner`'s default token approved for transfer by `spender`. */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Approve transfers of up to `amount` of default token. */ function approve(address spender, uint256 amount) external override returns (bool) { require(amount == 0 || _allowances[msg.sender][spender] == 0, "ERC20_1155Votes: potential double approval exploit"); _approve(msg.sender, spender, amount); return true; } /** * @dev Transfer `amount` of default token from sender to `to` account. */ function transfer(address to, uint256 amount) external override returns (bool) { _safeTransferFrom(msg.sender, to, _defaultToken[msg.sender], amount, ""); // secondary event for the ERC20 interface emit Transfer(msg.sender, to, amount); return true; } /** * @dev Transfer `amount` of common shares (token id == 0) from `from` account to `to` account. */ function transferFrom(address from, address to, uint256 amount) external override returns (bool) { require(_allowances[msg.sender][from] >= amount, "ERC20_1155Votes: transfer exceeds allowance"); _safeTransferFrom(from, to, _defaultToken[msg.sender], amount, ""); // secondary event for the ERC20 interface emit Transfer(from, to, amount); return true; } /** * @dev Get the voing power of an amount of tokens. */ function votingPower(uint256 /*id*/, uint256 amount) public view virtual returns (uint256) { return amount; } /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20_1155Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20_1155Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20_1155Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20_1155Votes: invalid nonce"); _delegate(signer, delegatee); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20_1155Votes: approve from the zero address"); require(spender != address(0), "ERC20_1155Votes: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Maximum aggregate token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224 amount) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual override { super._mint(account, id, amount, data); _aggregateSupply += amount; require(_aggregateSupply <= _maxSupply(), "ERC20_1155Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, votingPower(id, amount)); emit Transfer(address(0), account, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 id, uint256 amount) internal virtual override { super._burn(account, id, amount); _aggregateSupply -= amount; _writeCheckpoint(_totalSupplyCheckpoints, _subtract, votingPower(id, amount)); emit Transfer(account, address(0), amount); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._safeTransferFrom(from, to, id, amount, data); _moveVotingPower(delegates(from), delegates(to), votingPower(id, amount)); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = 0; for (uint32 id = 0; id < _n; ++id) { delegatorBalance += votingPower(id, balanceOf(delegator, id)); } _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } // EIP-2612 IERC20Permit ------------------------------------------------- /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC20Permit).interfaceId || interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC20Metadata).interfaceId || super.supportsInterface(interfaceId); } } // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } /** * @dev declare and safegaurd token allocations. */ abstract contract AllocationControl is AccessControl { using EnumerableSet for EnumerableSet.Bytes32Set; // ALLOCATOR_ROLE is the admin for granting allocation roles. bytes32 public constant ALLOCATOR_ROLE = keccak256("ALLOCATOR_ROLE"); // Other roles are defined dynamically to enable per-slice minting privileges. // For tracking mints against declared allocations. // struct Slice { uint256 tokenId; uint256 units; uint256 minted; } EnumerableSet.Bytes32Set private _roles; mapping(bytes32 => Slice) private _allocations; mapping(uint256 => uint256) private _supplyCapPerTokenId; uint256 private _totalSupplyCap; function allocationSlice(bytes32 role) public view returns (Slice memory) { return _allocations[role]; } function allocationTotalSupplyCap() public view returns (uint256) { return _totalSupplyCap; } function allocationSupplyCapPerTokenId(uint256 tokenId) public view returns (uint256) { return _supplyCapPerTokenId[tokenId]; } // Declares or adjusts a single allocation. // // 0. clear counters // 1. alter existing, recount units // 2. add new, count new units // 3. remove zeroed-out allocations only if not yet minted // function _allocationAllocate(bytes32 role, uint256 tokenId, uint256 units) internal { if (_roles.contains(role)) { // existing if (_allocations[role].minted > 0) { require(units >= _allocations[role].minted, "reallocation must include already minted slice"); require(tokenId == _allocations[role].tokenId, "cannot change allocation's tokenId if already minted"); } _totalSupplyCap -= _allocations[role].units; _supplyCapPerTokenId[tokenId] -= _allocations[role].units; _totalSupplyCap += units; _supplyCapPerTokenId[tokenId] += units; _allocations[role].units = units; } else { // new _roles.add(role); _setRoleAdmin(role, ALLOCATOR_ROLE); _totalSupplyCap += units; _supplyCapPerTokenId[tokenId] += units; _allocations[role] = Slice(tokenId, units, 0); } } function _onAllocationMint(bytes32 role, uint256 amount) internal { require(_allocations[role].minted + amount <= _allocations[role].units, "mint exceeds allocation"); _allocations[role].minted += amount; } } interface IAllocationMinter { function allocationSupplyAt(bytes32 role, uint256 timestamp) external view returns (uint256); function allocationAvailable(bytes32 role) external view returns (uint256); function allocationMint(address to, bytes32 role, uint256 amount) external; function allocationMinted(bytes32 role) external view returns (uint256); } /** * LG DAO - Main Protocol Token * * One Ring to rule them all, * One Ring to find them, * One Ring to bring them all * and in the ledger bind them.” * * ― J.K.W. Blockchain * * Through their voting power, LG token balances govern property directors and their * continuous reinvestment of net cash flows from multi-industry development projects * and associated Loci Bell (LB) tokens. (LB tokens are single-property multi-tranche * fixed-growth ERC1155 debt contracts.) * * LG's multi-class voting mechanism presents an ERC20 voting interface compatible with * popular on-chain governance UX while also presenting an ERC1155 multi-class interface * thereby enabling differentiation of expert voting power and common protocol equity. * * 65% of voting power is held by 97% of LG (a.k.a. ERC1155 LG). 35% of voting power is * controlled by DAO Foundation directors with less than 3% of LG (a.k.a. ERC1155 LGY). * Aggregate balances of ERC1155 LG/Y present as ERC20 LG token balances. * * LG token has built-in emission curves and allocation distribution by director role. * Tokens are minted on demand in their respective category according to distinct * emission curves or director grant. Chainges to allocations and curves may only occur * via governance vote. */ contract LG is ERC20_1155Votes, AllocationControl, IAllocationMinter { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; using EmissionCurves for EmissionCurves.Curve; bytes32 public constant RESERVE_ALLOCATION = keccak256("RESERVE_ALLOCATION"); bytes32 public constant ANON_ALLOCATION = keccak256("ANON_ALLOCATION"); bytes32 public constant LEGACY_ALLOCATION = keccak256("LEGACY_ALLOCATION"); bytes32 public constant RECM_ALLOCATION = keccak256("RECM_ALLOCATION"); bytes32 public constant WEB3_ALLOCATION = keccak256("WEB3_ALLOCATION"); bytes32 public constant DAO_ALLOCATION = keccak256("DAO_ALLOCATION"); bytes32 public constant Y_DAO_ALLOCATION = keccak256("Y_DAO_ALLOCATION"); bytes32 public constant LP_ALLOCATION = keccak256("LP_ALLOCATION"); bytes32 public constant TEAM_ALLOCATION = keccak256("TEAM_ALLOCATION"); mapping(bytes32 => EmissionCurves.Curve) curves; constructor(address daoMultisig, string memory baseURI) ERC20_1155Votes("Loci Global", "LG", baseURI, 2) { _grantRole(ALLOCATOR_ROLE, daoMultisig); _grantRole(ALLOCATOR_ROLE, msg.sender); _grantRole(WEB3_ALLOCATION, msg.sender); // LG DAO Long Term Reserves _allocationAllocate(RESERVE_ALLOCATION, 0, 185_000_000 * 1e18); // not minted // Anon Contributors _allocationAllocate( ANON_ALLOCATION, 0, 99_000_000 * 1e18); // Auction Emission // Legacy Contributors _allocationAllocate( LEGACY_ALLOCATION, 0, 51_500_000 * 1e18); // Gaurdians _allocationAllocate( RECM_ALLOCATION, 0, 24_400_000 * 1e18); _allocationAllocate( WEB3_ALLOCATION, 0, 15_100_000 * 1e18); // Core Technology _allocationAllocate( DAO_ALLOCATION, 0, 11_650_000 * 1e18); _allocationAllocate( Y_DAO_ALLOCATION, 1, 350_000 * 1e18); // 35% vote // Blockchain Launch _allocationAllocate( LP_ALLOCATION, 0, 20_700_000 * 1e18); // LP Reward Emission _allocationAllocate( TEAM_ALLOCATION, 0, 33_300_000 * 1e18); // Property, Operations, Agents // Theoretical caps if/when each allocation role mints 100% require(allocationTotalSupplyCap() == 441_000_000 * 1e18); // 185M non-mintable require(allocationSupplyCapPerTokenId(0) == 440_650_000 * 1e18); require(allocationSupplyCapPerTokenId(1) == 350_000 * 1e18); // Initial Emission Curves curves[ANON_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 26 * 7 * 86400, 30, // 6 months ramp-up e^3.0x 1 * 52 * 7 * 86400, // 1 year of max emissions 3 * 52 * 7 * 86400, 30); // 3 years of decay e^-3.0x curves[RECM_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 3 * 52 * 7 * 86400, 20, // 3 years of ramp-up e^2x 2 * 52 * 7 * 86400, // 2 years of max emissions 0, 0); curves[WEB3_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 3 * 52 * 7 * 86400, 20, // 3 years of ramp-up e^2x 2 * 52 * 7 * 86400, // 2 years of max emissions 0, 0); curves[DAO_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 3 * 52 * 7 * 86400, 20, // 3 years of ramp-up e^2x 2 * 52 * 7 * 86400, // 2 years of max emissions 0, 0); } function setURI(string memory newURI) public { _setURI(newURI); } function setCurve( bytes32 role, uint256 timeStart, uint32 durationGrowth, uint8 expGrowth, uint32 durationMax, uint32 durationDecay, uint8 expDecay ) public onlyRole(ALLOCATOR_ROLE) { curves[role] = EmissionCurves.newCurve(timeStart, durationGrowth, expGrowth, durationMax, durationDecay, expDecay); } function allocationAllocate(bytes32 role, uint256 id, uint256 units) public onlyRole(ALLOCATOR_ROLE) { require(id < 2, "invalid class"); _allocationAllocate(role, id, units); } function votingPower(uint256 id, uint256 amount) public view override returns (uint256) { require(id < 2, "invalid class"); return amount * (id == 1 ? 35 : 65) / allocationSupplyCapPerTokenId(id); } // IAllocationMinter ----------------------------------------------------- function allocationMint(address to, bytes32 role, uint256 amount) public override onlyRole(role) { Slice memory slice = allocationSlice(role); uint total = curves[role].calcGrowth(block.timestamp).mulu(slice.units * 1e5) / 1e5; uint256 available = total > slice.minted ? total - slice.minted : 0; require(amount <= available, "amount exceeds emissions available"); _onAllocationMint(role, amount); _mint(to, slice.tokenId, amount, ""); } function allocationSupplyAt(bytes32 role, uint256 timestamp) public view override returns (uint256) { return curves[role].calcGrowth(timestamp).mulu(allocationSlice(role).units * 1e5) / 1e5; } function allocationAvailable(bytes32 role) public view override returns (uint256) { Slice memory slice = allocationSlice(role); uint total = curves[role].calcGrowth(block.timestamp).mulu(slice.units * 1e5) / 1e5; return total > slice.minted ? total - slice.minted : 0; } function allocationMinted(bytes32 role) public view override returns (uint256) { return allocationSlice(role).minted; } // IERC165 --------------------------------------------------------------- /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC20_1155Votes, AccessControl) returns (bool) { return ERC20_1155Votes.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId); } }
LG DAO Long Term Reserves Anon Contributors Legacy Contributors Gaurdians Blockchain Launch Theoretical caps if/when each allocation role mints 100% Initial Emission Curves
{ _grantRole(ALLOCATOR_ROLE, daoMultisig); _grantRole(ALLOCATOR_ROLE, msg.sender); _grantRole(WEB3_ALLOCATION, msg.sender); _allocationAllocate( LEGACY_ALLOCATION, 0, 51_500_000 * 1e18); _allocationAllocate( RECM_ALLOCATION, 0, 24_400_000 * 1e18); _allocationAllocate( DAO_ALLOCATION, 0, 11_650_000 * 1e18); require(allocationSupplyCapPerTokenId(0) == 440_650_000 * 1e18); require(allocationSupplyCapPerTokenId(1) == 350_000 * 1e18); curves[ANON_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, curves[RECM_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 0, 0); curves[WEB3_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 0, 0); curves[DAO_ALLOCATION] = EmissionCurves.newCurve( block.timestamp, 0, 0); }
2,390,092
[ 1, 48, 43, 463, 20463, 3407, 6820, 1124, 264, 3324, 1922, 265, 735, 665, 13595, 22781, 735, 665, 13595, 611, 28659, 3211, 634, 3914, 5639, 14643, 1021, 479, 88, 1706, 15788, 309, 19, 13723, 1517, 13481, 2478, 312, 28142, 2130, 9, 10188, 512, 3951, 7251, 3324, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 389, 16243, 2996, 12, 1013, 29450, 3575, 67, 16256, 16, 15229, 5049, 291, 360, 1769, 203, 3639, 389, 16243, 2996, 12, 1013, 29450, 3575, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 16243, 2996, 12, 14778, 23, 67, 1013, 15277, 16, 1234, 18, 15330, 1769, 203, 203, 203, 203, 203, 203, 203, 3639, 389, 29299, 27483, 12, 5380, 43, 2226, 61, 67, 1013, 15277, 16, 374, 16, 225, 21119, 67, 12483, 67, 3784, 380, 404, 73, 2643, 1769, 203, 203, 203, 3639, 389, 29299, 27483, 12, 282, 2438, 9611, 67, 1013, 15277, 16, 374, 16, 225, 4248, 67, 16010, 67, 3784, 380, 404, 73, 2643, 1769, 203, 3639, 389, 29299, 27483, 12, 565, 463, 20463, 67, 1013, 15277, 16, 374, 16, 225, 4648, 67, 26, 3361, 67, 3784, 380, 404, 73, 2643, 1769, 203, 203, 203, 203, 203, 3639, 2583, 12, 29299, 3088, 1283, 4664, 2173, 1345, 548, 12, 20, 13, 225, 422, 1059, 7132, 67, 26, 3361, 67, 3784, 380, 404, 73, 2643, 1769, 203, 3639, 2583, 12, 29299, 3088, 1283, 4664, 2173, 1345, 548, 12, 21, 13, 225, 422, 377, 890, 3361, 67, 3784, 380, 404, 73, 2643, 1769, 203, 203, 203, 3639, 24106, 63, 1258, 673, 67, 1013, 15277, 65, 273, 512, 3951, 2408, 3324, 18, 2704, 9423, 12, 203, 5411, 1203, 18, 5508, 16, 203, 203, 3639, 24106, 63, 862, 9611, 67, 1013, 15277, 65, 273, 512, 3951, 2408, 3324, 18, 2704, 9423, 12, 203, 5411, 1203, 18, 5508, 16, 203, 5411, 374, 16, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import '@openzeppelin/contracts/utils/Address.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; import './ERC20.sol'; /** * @notice ERC20 token with cost basis tracking and restricted loss-taking */ contract Dogstonks is ERC20 { using Address for address payable; string public override name = 'DOGSTONKS (dogstonks.com)'; string public override symbol = 'DOGSTONKS'; address private constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint private constant SUPPLY = 1e12 ether; address private _owner; address private _pair; uint private _openedAt; uint private _closedAt; mapping (address => uint) private _basisOf; mapping (address => uint) public cooldownOf; uint private _initialBasis; uint private _ath; uint private _athTimestamp; struct Minting { address recipient; uint amount; } /** * @notice deploy */ constructor () payable { _owner = msg.sender; // setup uniswap pair and store address _pair = IUniswapV2Factory( IUniswapV2Router02(UNISWAP_ROUTER).factory() ).createPair(WETH, address(this)); // prepare to add liquidity _approve(address(this), UNISWAP_ROUTER, SUPPLY); // prepare to remove liquidity IERC20(_pair).approve(UNISWAP_ROUTER, type(uint).max); } receive () external payable {} /** * @notice get cost basis for given address * @param account address to query * @return cost basis */ function basisOf ( address account ) public view returns (uint) { uint basis = _basisOf[account]; if (basis == 0 && balanceOf(account) > 0) { basis = _initialBasis; } return basis; } /** * @notice mint team tokens prior to opening of trade * @param mintings structured minting data (recipient, amount) */ function mint ( Minting[] calldata mintings ) external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); uint mintedSupply; for (uint i; i < mintings.length; i++) { Minting memory m = mintings[i]; uint amount = m.amount; address recipient = m.recipient; mintedSupply += amount; _balances[recipient] += amount; emit Transfer(address(0), recipient, amount); } _totalSupply += mintedSupply; } /** * @notice open trading * @dev sender must be owner * @dev trading must not yet have been opened */ function open () external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); _openedAt = block.timestamp; // add liquidity, set initial cost basis _mint(address(this), SUPPLY - totalSupply()); _initialBasis = (1 ether) * address(this).balance / balanceOf(address(this)); IUniswapV2Router02( UNISWAP_ROUTER ).addLiquidityETH{ value: address(this).balance }( address(this), balanceOf(address(this)), 0, 0, address(this), block.timestamp ); } /** * @notice close trading * @dev trading must not yet have been closed * @dev minimum time since open must have elapsed */ function close () external { require(_openedAt != 0, 'ERR: not yet opened'); require(_closedAt == 0, 'ERR: already closed'); require(block.timestamp > _openedAt + (1 days), 'ERR: too soon'); _closedAt = block.timestamp; require( block.timestamp > _athTimestamp + (1 weeks), 'ERR: recent ATH' ); (uint token, ) = IUniswapV2Router02( UNISWAP_ROUTER ).removeLiquidityETH( address(this), IERC20(_pair).balanceOf(address(this)), 0, 0, address(this), block.timestamp ); _burn(address(this), token); } /** * @notice exchange DOGSTONKS for proportion of ETH in contract * @dev trading must have been closed */ function liquidate () external { require(_closedAt > 0, 'ERR: not yet closed'); uint balance = balanceOf(msg.sender); require(balance != 0, 'ERR: zero balance'); uint payout = address(this).balance * balance / totalSupply(); _burn(msg.sender, balance); payable(msg.sender).sendValue(payout); } /** * @notice withdraw remaining ETH from contract * @dev trading must have been closed * @dev minimum time since close must have elapsed */ function liquidateUnclaimed () external { require(_closedAt > 0, 'ERR: not yet closed'); require(block.timestamp > _closedAt + (52 weeks), 'ERR: too soon'); payable(_owner).sendValue(address(this).balance); } function _beforeTokenTransfer ( address from, address to, uint amount ) override internal { super._beforeTokenTransfer(from, to, amount); // ignore minting and burning if (from == address(0) || to == address(0)) return; // ignore add/remove liquidity if (from == address(this) || to == address(this)) return; if (from == UNISWAP_ROUTER || to == UNISWAP_ROUTER) return; require(_openedAt > 0); require( msg.sender == UNISWAP_ROUTER || msg.sender == _pair, 'ERR: sender must be uniswap' ); require(amount <= 5e9 ether /* revert message not returned by Uniswap */); address[] memory path = new address[](2); if (from == _pair) { require(cooldownOf[to] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[to] = block.timestamp + (5 minutes); path[0] = WETH; path[1] = address(this); uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsIn( amount, path ); uint balance = balanceOf(to); uint fromBasis = (1 ether) * amounts[0] / amount; _basisOf[to] = (fromBasis * amount + basisOf(to) * balance) / (amount + balance); if (fromBasis > _ath) { _ath = fromBasis; _athTimestamp = block.timestamp; } } else if (to == _pair) { // blacklist Vitalik Buterin require(from != 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B /* revert message not returned by Uniswap */); require(cooldownOf[from] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[from] = block.timestamp + (5 minutes); path[0] = address(this); path[1] = WETH; uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsOut( amount, path ); require(basisOf(from) <= (1 ether) * amounts[1] / amount /* revert message not returned by Uniswap */); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.4._ */ 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.4._ */ 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); } } } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
* @notice ERC20 token with cost basis tracking and restricted loss-taking/
contract Dogstonks is ERC20 { using Address for address payable; string public override name = 'DOGSTONKS (dogstonks.com)'; string public override symbol = 'DOGSTONKS'; address private constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint private constant SUPPLY = 1e12 ether; address private _owner; address private _pair; uint private _openedAt; uint private _closedAt; mapping (address => uint) private _basisOf; mapping (address => uint) public cooldownOf; uint private _initialBasis; uint private _ath; uint private _athTimestamp; struct Minting { address recipient; uint amount; } constructor () payable { _owner = msg.sender; _pair = IUniswapV2Factory( IUniswapV2Router02(UNISWAP_ROUTER).factory() ).createPair(WETH, address(this)); _approve(address(this), UNISWAP_ROUTER, SUPPLY); IERC20(_pair).approve(UNISWAP_ROUTER, type(uint).max); } receive () external payable {} function basisOf ( address account ) public view returns (uint) { uint basis = _basisOf[account]; if (basis == 0 && balanceOf(account) > 0) { basis = _initialBasis; } return basis; } function basisOf ( address account ) public view returns (uint) { uint basis = _basisOf[account]; if (basis == 0 && balanceOf(account) > 0) { basis = _initialBasis; } return basis; } function mint ( Minting[] calldata mintings ) external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); uint mintedSupply; for (uint i; i < mintings.length; i++) { Minting memory m = mintings[i]; uint amount = m.amount; address recipient = m.recipient; mintedSupply += amount; _balances[recipient] += amount; emit Transfer(address(0), recipient, amount); } _totalSupply += mintedSupply; } function mint ( Minting[] calldata mintings ) external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); uint mintedSupply; for (uint i; i < mintings.length; i++) { Minting memory m = mintings[i]; uint amount = m.amount; address recipient = m.recipient; mintedSupply += amount; _balances[recipient] += amount; emit Transfer(address(0), recipient, amount); } _totalSupply += mintedSupply; } function open () external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); _openedAt = block.timestamp; _mint(address(this), SUPPLY - totalSupply()); _initialBasis = (1 ether) * address(this).balance / balanceOf(address(this)); IUniswapV2Router02( UNISWAP_ROUTER ).addLiquidityETH{ value: address(this).balance }( address(this), balanceOf(address(this)), 0, 0, address(this), block.timestamp ); } function open () external { require(msg.sender == _owner, 'ERR: sender must be owner'); require(_openedAt == 0, 'ERR: already opened'); _openedAt = block.timestamp; _mint(address(this), SUPPLY - totalSupply()); _initialBasis = (1 ether) * address(this).balance / balanceOf(address(this)); IUniswapV2Router02( UNISWAP_ROUTER ).addLiquidityETH{ value: address(this).balance }( address(this), balanceOf(address(this)), 0, 0, address(this), block.timestamp ); } function close () external { require(_openedAt != 0, 'ERR: not yet opened'); require(_closedAt == 0, 'ERR: already closed'); require(block.timestamp > _openedAt + (1 days), 'ERR: too soon'); _closedAt = block.timestamp; require( block.timestamp > _athTimestamp + (1 weeks), 'ERR: recent ATH' ); (uint token, ) = IUniswapV2Router02( UNISWAP_ROUTER ).removeLiquidityETH( address(this), IERC20(_pair).balanceOf(address(this)), 0, 0, address(this), block.timestamp ); _burn(address(this), token); } function liquidate () external { require(_closedAt > 0, 'ERR: not yet closed'); uint balance = balanceOf(msg.sender); require(balance != 0, 'ERR: zero balance'); uint payout = address(this).balance * balance / totalSupply(); _burn(msg.sender, balance); payable(msg.sender).sendValue(payout); } function liquidateUnclaimed () external { require(_closedAt > 0, 'ERR: not yet closed'); require(block.timestamp > _closedAt + (52 weeks), 'ERR: too soon'); payable(_owner).sendValue(address(this).balance); } function _beforeTokenTransfer ( address from, address to, uint amount ) override internal { super._beforeTokenTransfer(from, to, amount); if (from == address(0) || to == address(0)) return; if (from == address(this) || to == address(this)) return; if (from == UNISWAP_ROUTER || to == UNISWAP_ROUTER) return; require(_openedAt > 0); require( msg.sender == UNISWAP_ROUTER || msg.sender == _pair, 'ERR: sender must be uniswap' ); require(amount <= 5e9 ether /* revert message not returned by Uniswap */); address[] memory path = new address[](2); if (from == _pair) { require(cooldownOf[to] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[to] = block.timestamp + (5 minutes); path[0] = WETH; path[1] = address(this); uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsIn( amount, path ); uint balance = balanceOf(to); uint fromBasis = (1 ether) * amounts[0] / amount; _basisOf[to] = (fromBasis * amount + basisOf(to) * balance) / (amount + balance); if (fromBasis > _ath) { _ath = fromBasis; _athTimestamp = block.timestamp; } require(cooldownOf[from] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[from] = block.timestamp + (5 minutes); path[0] = address(this); path[1] = WETH; uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsOut( amount, path ); require(basisOf(from) <= (1 ether) * amounts[1] / amount /* revert message not returned by Uniswap */); } } function _beforeTokenTransfer ( address from, address to, uint amount ) override internal { super._beforeTokenTransfer(from, to, amount); if (from == address(0) || to == address(0)) return; if (from == address(this) || to == address(this)) return; if (from == UNISWAP_ROUTER || to == UNISWAP_ROUTER) return; require(_openedAt > 0); require( msg.sender == UNISWAP_ROUTER || msg.sender == _pair, 'ERR: sender must be uniswap' ); require(amount <= 5e9 ether /* revert message not returned by Uniswap */); address[] memory path = new address[](2); if (from == _pair) { require(cooldownOf[to] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[to] = block.timestamp + (5 minutes); path[0] = WETH; path[1] = address(this); uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsIn( amount, path ); uint balance = balanceOf(to); uint fromBasis = (1 ether) * amounts[0] / amount; _basisOf[to] = (fromBasis * amount + basisOf(to) * balance) / (amount + balance); if (fromBasis > _ath) { _ath = fromBasis; _athTimestamp = block.timestamp; } require(cooldownOf[from] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[from] = block.timestamp + (5 minutes); path[0] = address(this); path[1] = WETH; uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsOut( amount, path ); require(basisOf(from) <= (1 ether) * amounts[1] / amount /* revert message not returned by Uniswap */); } } function _beforeTokenTransfer ( address from, address to, uint amount ) override internal { super._beforeTokenTransfer(from, to, amount); if (from == address(0) || to == address(0)) return; if (from == address(this) || to == address(this)) return; if (from == UNISWAP_ROUTER || to == UNISWAP_ROUTER) return; require(_openedAt > 0); require( msg.sender == UNISWAP_ROUTER || msg.sender == _pair, 'ERR: sender must be uniswap' ); require(amount <= 5e9 ether /* revert message not returned by Uniswap */); address[] memory path = new address[](2); if (from == _pair) { require(cooldownOf[to] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[to] = block.timestamp + (5 minutes); path[0] = WETH; path[1] = address(this); uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsIn( amount, path ); uint balance = balanceOf(to); uint fromBasis = (1 ether) * amounts[0] / amount; _basisOf[to] = (fromBasis * amount + basisOf(to) * balance) / (amount + balance); if (fromBasis > _ath) { _ath = fromBasis; _athTimestamp = block.timestamp; } require(cooldownOf[from] < block.timestamp /* revert message not returned by Uniswap */); cooldownOf[from] = block.timestamp + (5 minutes); path[0] = address(this); path[1] = WETH; uint[] memory amounts = IUniswapV2Router02(UNISWAP_ROUTER).getAmountsOut( amount, path ); require(basisOf(from) <= (1 ether) * amounts[1] / amount /* revert message not returned by Uniswap */); } } } else if (to == _pair) { require(from != 0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B /* revert message not returned by Uniswap */); }
6,275,519
[ 1, 654, 39, 3462, 1147, 598, 6991, 10853, 11093, 471, 15693, 8324, 17, 88, 6159, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 717, 334, 265, 7904, 353, 4232, 39, 3462, 288, 203, 225, 1450, 5267, 364, 1758, 8843, 429, 31, 203, 203, 225, 533, 1071, 3849, 508, 273, 296, 3191, 43, 882, 673, 47, 55, 261, 20330, 334, 265, 7904, 18, 832, 2506, 31, 203, 225, 533, 1071, 3849, 3273, 273, 296, 3191, 43, 882, 673, 47, 55, 13506, 203, 203, 225, 1758, 3238, 5381, 5019, 5127, 59, 2203, 67, 1457, 1693, 654, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 225, 1758, 3238, 5381, 678, 1584, 44, 273, 374, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 31, 203, 203, 225, 2254, 3238, 5381, 16459, 23893, 273, 404, 73, 2138, 225, 2437, 31, 203, 203, 225, 1758, 3238, 389, 8443, 31, 203, 203, 225, 1758, 3238, 389, 6017, 31, 203, 203, 225, 2254, 3238, 389, 25304, 861, 31, 203, 225, 2254, 3238, 389, 12204, 861, 31, 203, 203, 225, 2874, 261, 2867, 516, 2254, 13, 3238, 389, 23774, 951, 31, 203, 225, 2874, 261, 2867, 516, 2254, 13, 1071, 27367, 2378, 951, 31, 203, 203, 225, 2254, 3238, 389, 6769, 11494, 291, 31, 203, 203, 225, 2254, 3238, 389, 421, 31, 203, 225, 2254, 3238, 389, 421, 4921, 31, 203, 203, 203, 225, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; 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"); (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"); (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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; /// @notice Minimal interface for BentoBox token vault interactions - `token` is aliased as `address` from `IERC20` for code simplicity. interface IBentoBoxMinimal { struct Rebase { uint128 elastic; uint128 base; } struct StrategyData { uint64 strategyStartDate; uint64 targetPercentage; uint128 balance; // the balance of the strategy that BentoBox thinks is in there } function strategyData(address token) external view returns (StrategyData memory); /// @notice Balance per ERC-20 token per account in shares. function balanceOf(address, address) external view returns (uint256); /// @notice Deposit an amount of `token` represented in either `amount` or `share`. /// @param token_ The ERC-20 token to deposit. /// @param from which account to pull the tokens. /// @param to which account to push the tokens. /// @param amount Token amount in native representation to deposit. /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`. /// @return amountOut The amount deposited. /// @return shareOut The deposited amount repesented in shares. function deposit( address token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); /// @notice Withdraws an amount of `token` from a user account. /// @param token_ The ERC-20 token to withdraw. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied. /// @param share Like above, but `share` takes precedence over `amount`. function withdraw( address token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); /// @notice Transfer shares from a user account to another one. /// @param token The ERC-20 token to transfer. /// @param from which user to pull the tokens. /// @param to which user to push the tokens. /// @param share The amount of `token` in shares. function transfer( address token, address from, address to, uint256 share ) external; /// @dev Helper function to represent an `amount` of `token` in shares. /// @param token The ERC-20 token. /// @param amount The `token` amount. /// @param roundUp If the result `share` should be rounded up. /// @return share The token amount represented in shares. function toShare( address token, uint256 amount, bool roundUp ) external view returns (uint256 share); /// @dev Helper function to represent shares back into the `token` amount. /// @param token The ERC-20 token. /// @param share The amount of shares. /// @param roundUp If the result should be rounded up. /// @return amount The share amount back into native representation. function toAmount( address token, uint256 share, bool roundUp ) external view returns (uint256 amount); /// @notice Registers this contract so that users can approve it for the BentoBox. function registerProtocol() external; function totals(address token) external view returns (Rebase memory); function harvest( address token, bool balance, uint256 maxChangeAmount ) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; interface IStrategy { /// @notice Send the assets to the Strategy and call skim to invest them. /// @param amount The amount of tokens to invest. function skim(uint256 amount) external; /// @notice Harvest any profits made converted to the asset and pass them to the caller. /// @param balance The amount of tokens the caller thinks it has invested. /// @param sender The address of the initiator of this transaction. Can be used for reimbursements, etc. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. function harvest(uint256 balance, address sender) external returns (int256 amountAdded); /// @notice Withdraw assets. The returned amount can differ from the requested amount due to rounding. /// @dev The `actualAmount` should be very close to the amount. /// The difference should NOT be used to report a loss. That's what harvest is for. /// @param amount The requested amount the caller wants to withdraw. /// @return actualAmount The real amount that is withdrawn. function withdraw(uint256 amount) external returns (uint256 actualAmount); /// @notice Withdraw all assets in the safest way possible. This shouldn't fail. /// @param balance The amount of tokens the caller thinks it has invested. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. function exit(uint256 balance) external returns (int256 amountAdded); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; interface IUniswapV2Pair { function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.7; import "../interfaces/IUniswapV2Pair.sol"; /* The following library is modified from @sushiswap/core/contracts/uniswapv2/libraries/UniswapV2Library.sol changes: - remove SafeMathUniswap library and replace all usage of it with basic operations - change casting from uint to bytes20 in pair address calculation and shift by 96 bits before casting */ library UniswapV2Library { // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); // Since Solidity 0.8.0 explicit conversions from literals larger than type(uint160).max to address are disallowed. // https://docs.soliditylang.org/en/develop/080-breaking-changes.html#new-restrictions pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB, bytes32 pairCodeHash ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); amountB = (amountA * reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = (reserveIn * 1000) + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path, bytes32 pairCodeHash ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-3.0-or-later // solhint-disable reason-string, avoid-low-level-calls, const-name-snakecase pragma solidity 0.8.7; import "../interfaces/IStrategy.sol"; import "../interfaces/IUniswapV2Pair.sol"; import "../interfaces/IBentoBoxMinimal.sol"; import "../libraries/UniswapV2Library.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IAnchorRouter { function depositStable(uint256 _amount) external; function redeemStable(uint256 _amount) external; } interface IExchangeRateFeeder { function exchangeRateOf(address _token, bool _simulate) external view returns (uint256); } abstract contract BaseStrategy is IStrategy, Ownable { using SafeERC20 for IERC20; address public immutable strategyToken; address public immutable bentoBox; address public immutable factory; address public immutable bridgeToken; bool public exited; /// @dev After bentobox 'exits' the strategy harvest, skim and withdraw functions can no loner be called uint256 public maxBentoBoxBalance; /// @dev Slippage protection when calling harvest mapping(address => bool) public strategyExecutors; /// @dev EOAs that can execute safeHarvest event LogConvert(address indexed server, address indexed token0, address indexed token1, uint256 amount0, uint256 amount1); event LogSetStrategyExecutor(address indexed executor, bool allowed); /** @param _strategyToken Address of the underlying token the strategy invests. @param _bentoBox BentoBox address. @param _factory SushiSwap factory. @param _bridgeToken An intermedieary token for swapping any rewards into the underlying token. @param _strategyExecutor an EOA that will execute the safeHarvest function. @dev factory and bridgeToken can be address(0) if we don't expect rewards we would need to swap */ constructor( address _strategyToken, address _bentoBox, address _factory, address _bridgeToken, address _strategyExecutor ) { strategyToken = _strategyToken; bentoBox = _bentoBox; factory = _factory; bridgeToken = _bridgeToken; if (_strategyExecutor != address(0)) { strategyExecutors[_strategyExecutor] = true; emit LogSetStrategyExecutor(_strategyExecutor, true); } } //** Strategy implementation: override the following functions: */ /// @notice Invests the underlying asset. /// @param amount The amount of tokens to invest. /// @dev Assume the contract's balance is greater than the amount function _skim(uint256 amount) internal virtual; /// @notice Harvest any profits made and transfer them to address(this) or report a loss /// @param balance The amount of tokens that have been invested. /// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`. /// @dev amountAdded can be left at 0 when reporting profits (gas savings). /// amountAdded should not reflect any rewards or tokens the strategy received. /// Calcualte the amount added based on what the current deposit is worth. /// (The Base Strategy harvest function accounts for rewards). function _harvest(uint256 balance) internal virtual returns (int256 amountAdded); /// @dev Withdraw the requested amount of the underlying tokens to address(this). /// @param amount The requested amount we want to withdraw. function _withdraw(uint256 amount) internal virtual; /// @notice Withdraw the maximum available amount of the invested assets to address(this). /// @dev This shouldn't revert (use try catch). function _exit() internal virtual; /// @notice Claim any rewards reward tokens and optionally sell them for the underlying token. /// @dev Doesn't need to be implemented if we don't expect any rewards. function _harvestRewards() internal virtual {} //** End strategy implementation */ modifier isActive() { require(!exited, "BentoBox Strategy: exited"); _; } modifier onlyBentoBox() { require(msg.sender == bentoBox, "BentoBox Strategy: only BentoBox"); _; } modifier onlyExecutor() { require(strategyExecutors[msg.sender], "BentoBox Strategy: only Executors"); _; } function setStrategyExecutor(address executor, bool value) external onlyOwner { strategyExecutors[executor] = value; emit LogSetStrategyExecutor(executor, value); } /// @inheritdoc IStrategy function skim(uint256 amount) external override { _skim(amount); } /// @notice Harvest profits while preventing a sandwich attack exploit. /// @param maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox. /// @param rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation. /// @param maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox. /// @param harvestRewards If we want to claim any accrued reward tokens /// @dev maxBalance can be set to 0 to keep the previous value. /// @dev maxChangeAmount can be set to 0 to allow for full rebalancing. function safeHarvest( uint256 maxBalance, bool rebalance, uint256 maxChangeAmount, bool harvestRewards ) external onlyExecutor { if (harvestRewards) { _harvestRewards(); } if (maxBalance > 0) { maxBentoBoxBalance = maxBalance; } IBentoBoxMinimal(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount); } /// @inheritdoc IStrategy function withdraw(uint256 amount) external override isActive onlyBentoBox returns (uint256 actualAmount) { _withdraw(amount); /// @dev Make sure we send and report the exact same amount of tokens by using balanceOf. actualAmount = IERC20(strategyToken).balanceOf(address(this)); IERC20(strategyToken).safeTransfer(bentoBox, actualAmount); } /// @inheritdoc IStrategy /// @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) { _exit(); /// @dev Check balance of token on the contract. uint256 actualBalance = IERC20(strategyToken).balanceOf(address(this)); /// @dev Calculate tokens added (or lost). amountAdded = int256(actualBalance) - int256(balance); /// @dev Transfer all tokens to bentoBox. IERC20(strategyToken).safeTransfer(bentoBox, actualBalance); /// @dev Flag as exited, allowing the owner to manually deal with any amounts available later. exited = true; } /** @dev After exited, the owner can perform ANY call. This is to rescue any funds that didn't get released during exit or got earned afterwards due to vesting or airdrops, etc. */ function afterExit( address to, uint256 value, bytes memory data ) public onlyOwner returns (bool success) { require(exited, "BentoBox Strategy: not exited"); (success, ) = to.call{value: value}(data); } } contract USTStrategyV2 is BaseStrategy { using SafeERC20 for IERC20; IAnchorRouter public constant router = IAnchorRouter(0xcEF9E167d3f8806771e9bac1d4a0d568c39a9388); IExchangeRateFeeder public feeder = IExchangeRateFeeder(0x24a76073Ab9131b25693F3b75dD1ce996fd3116c); IERC20 public constant UST = IERC20(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD); IERC20 public constant aUST = IERC20(0xa8De3e3c934e2A1BB08B010104CcaBBD4D6293ab); address private constant degenBox = 0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce; uint256 public fee; // fees on ust address public feeCollector; constructor(address strategyExecutor, address _feeCollector) BaseStrategy(address(UST), degenBox, address(0), address(0), strategyExecutor) { UST.approve(address(router), type(uint256).max); aUST.approve(address(router), type(uint256).max); feeCollector = _feeCollector; fee = 10; } function _skim(uint256 amount) internal override { router.depositStable(amount); } /** @inheritdoc IStrategy @dev Only BentoBox can call harvest on this strategy. @dev Ensures that (1) the caller was this contract (called through the safeHarvest function) and (2) that we are not being frontrun by a large BentoBox deposit when harvesting profits. */ function harvest(uint256 balance, address sender) external override isActive onlyBentoBox returns (int256) { /** @dev Don't revert if conditions aren't met in order to allow BentoBox to continiue execution as it might need to do a rebalance. */ if (sender == address(this) && IBentoBoxMinimal(bentoBox).totals(strategyToken).elastic <= maxBentoBoxBalance && balance > 0) { int256 amount = _harvest(balance); /** @dev Since harvesting of rewards is accounted for seperately we might also have some underlying tokens in the contract that the _harvest call doesn't report. E.g. reward tokens that have been sold into the underlying tokens which are now sitting in the contract. Meaning the amount returned by the internal _harvest function isn't necessary the final profit/loss amount */ uint256 contractBalance = IERC20(strategyToken).balanceOf(address(this)); if (amount >= 0) { // _harvest reported a profit if (contractBalance >= uint256(amount)) { uint256 feeAmount = (uint256(amount) * fee) / 100; uint256 toTransfer = uint256(amount) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, uint256(toTransfer)); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return (amount); } else { uint256 feeAmount = (uint256(contractBalance) * fee) / 100; uint256 toTransfer = uint256(contractBalance) - feeAmount; IERC20(strategyToken).safeTransfer(bentoBox, toTransfer); IERC20(strategyToken).safeTransfer(feeCollector, feeAmount); return int256(contractBalance); } } else { // we made a loss return amount; } } return int256(0); } function _harvest(uint256 balance) internal view override returns (int256) { uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 keep = toAUST(balance, exchangeRate); uint256 total = aUST.balanceOf(address(this)) + toAUST(UST.balanceOf(address(this)), exchangeRate); return int256(toUST(total, exchangeRate)) - int256(toUST(keep, exchangeRate)); } function _withdraw(uint256 amount) internal override {} function redeemEarnings() external onlyExecutor { uint256 balanceToKeep = IBentoBoxMinimal(bentoBox).strategyData(address(UST)).balance; uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 liquid = UST.balanceOf(address(this)); uint256 total = toUST(aUST.balanceOf(address(this)), exchangeRate) + liquid; if (total > balanceToKeep) { router.redeemStable(toAUST(total - balanceToKeep - liquid, exchangeRate)); } } function safeDeposit(uint256 amount) external onlyExecutor { _skim(amount); } function safeWithdraw(uint256 amount) external onlyExecutor { uint256 exchangeRate = feeder.exchangeRateOf(address(UST), true); uint256 requested = toAUST(amount, exchangeRate); router.redeemStable(requested); } function safeWithdrawFromAUST(uint256 amount) external onlyExecutor { router.redeemStable(amount); } function updateExchangeRateFeeder(IExchangeRateFeeder feeder_) external onlyOwner { feeder = feeder_; } function setFeeCollector(address _feeCollector, uint256 _fee) external onlyOwner { require(_fee <= 50, "max fee is 50"); feeCollector = _feeCollector; fee = _fee; } function _exit() internal override { try router.redeemStable(aUST.balanceOf(address(this))) {} catch {} } function toUST(uint256 amount, uint256 exchangeRate) public pure returns (uint256) { return (amount * exchangeRate) / 1e18; } function toAUST(uint256 amount, uint256 exchangeRate) public pure returns (uint256) { return (amount * 1e18) / exchangeRate; } }
@inheritdoc IStrategy @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times
function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) { _exit(); uint256 actualBalance = IERC20(strategyToken).balanceOf(address(this)); amountAdded = int256(actualBalance) - int256(balance); IERC20(strategyToken).safeTransfer(bentoBox, actualBalance); exited = true;
1,332,819
[ 1, 36, 10093, 467, 4525, 225, 741, 486, 999, 15083, 9606, 2674, 31, 1699, 324, 319, 27570, 358, 745, 6252, 18, 8593, 1435, 3229, 4124, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2427, 12, 11890, 5034, 11013, 13, 3903, 3849, 1338, 38, 29565, 3514, 1135, 261, 474, 5034, 3844, 8602, 13, 288, 203, 3639, 389, 8593, 5621, 203, 3639, 2254, 5034, 3214, 13937, 273, 467, 654, 39, 3462, 12, 14914, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 3844, 8602, 273, 509, 5034, 12, 18672, 13937, 13, 300, 509, 5034, 12, 12296, 1769, 203, 3639, 467, 654, 39, 3462, 12, 14914, 1345, 2934, 4626, 5912, 12, 70, 29565, 3514, 16, 3214, 13937, 1769, 203, 3639, 21590, 273, 638, 31, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x93aBdFcbBA58Ba0B901d8eC6E023491E264E597b/sources/MOONDUSTChef.sol
Deposit LP tokens to MasterChef for MOONDUST allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMOONDUSTPerShare).div(1e12).sub(user.rewardDebt); safeMOONDUSTTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accMOONDUSTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
3,705,069
[ 1, 758, 1724, 511, 52, 2430, 358, 13453, 39, 580, 74, 364, 16070, 673, 40, 5996, 13481, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 309, 261, 1355, 18, 8949, 405, 374, 13, 288, 203, 5411, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 5980, 673, 40, 5996, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 5411, 4183, 5980, 673, 40, 5996, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 289, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 1265, 12, 2867, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 24899, 8949, 1769, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 5980, 673, 40, 5996, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xACA3109120c750F65b435Df7936AD0630a586061/sources/polyNFT.sol
RELEASE THE LOOGIES!
constructor() public ERC721("Buddies", "BUD") { } mapping (uint256 => bytes3) public color; mapping (uint256 => uint256) public chubbiness; uint256 mintDeadline = block.timestamp + 24 hours;
4,777,612
[ 1, 30762, 12786, 1806, 13369, 8805, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 1435, 1071, 4232, 39, 27, 5340, 2932, 38, 20567, 606, 3113, 315, 3000, 40, 7923, 288, 203, 225, 289, 203, 203, 225, 2874, 261, 11890, 5034, 516, 1731, 23, 13, 1071, 2036, 31, 203, 225, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 1071, 462, 373, 4757, 403, 31, 203, 203, 225, 2254, 5034, 312, 474, 15839, 273, 1203, 18, 5508, 397, 4248, 7507, 31, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./base/Controllable.sol"; import "sol-temple/src/tokens/ERC721.sol"; import "sol-temple/src/tokens/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title Ape Runners RUN /// @author naomsa <https://twitter.com/naomsa666> contract ApeRunnersRUN is Ownable, Pausable, Controllable, ERC20("Ape Runners", "RUN", 18, "1") { /* -------------------------------------------------------------------------- */ /* Airdrop Details */ /* -------------------------------------------------------------------------- */ /// @notice Ape Runners contract. ERC721 public immutable apeRunners; /// @notice Ape Runner id => claimed airdrop. mapping(uint256 => bool) public airdroped; constructor(address newApeRunners) { apeRunners = ERC721(newApeRunners); } /* -------------------------------------------------------------------------- */ /* Airdrop Logic */ /* -------------------------------------------------------------------------- */ /// @notice Claim pending airdrop for each Ape Runner. /// @param ids Ape Runner token ids to claim airdrop. function claim(uint256[] memory ids) external { uint256 pending; for (uint256 i; i < ids.length; i++) { require(apeRunners.ownerOf(ids[i]) == msg.sender, "Not the token owner"); require(!airdroped[ids[i]], "Airdrop already claimed"); airdroped[ids[i]] = true; pending += 150 ether; } super._mint(msg.sender, pending); } /* -------------------------------------------------------------------------- */ /* Owner Logic */ /* -------------------------------------------------------------------------- */ /// @notice Add or edit contract controllers. /// @param addrs Array of addresses to be added/edited. /// @param state New controller state of addresses. function setControllers(address[] calldata addrs, bool state) external onlyOwner { for (uint256 i; i < addrs.length; i++) super._setController(addrs[i], state); } /// @notice Switch the contract paused state between paused and unpaused. function togglePaused() external onlyOwner { if (paused()) _unpause(); else _pause(); } /* -------------------------------------------------------------------------- */ /* ERC-20 Logic */ /* -------------------------------------------------------------------------- */ /// @notice Mint tokens. /// @param to Address to get tokens minted to. /// @param value Number of tokens to be minted. function mint(address to, uint256 value) external onlyController { super._mint(to, value); } /// @notice Burn tokens. /// @param from Address to get tokens burned from. /// @param value Number of tokens to be burned. function burn(address from, uint256 value) external onlyController { super._burn(from, value); } /// @notice See {ERC20-_beforeTokenTransfer}. /// @dev Overriden to block transactions while the contract is paused (avoiding bugs). function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// @title Controllable abstract contract Controllable { /// @notice address => is controller. mapping(address => bool) private _isController; /// @notice Require the caller to be a controller. modifier onlyController() { require( _isController[msg.sender], "Controllable: Caller is not a controller" ); _; } /// @notice Check if `addr` is a controller. function isController(address addr) public view returns (bool) { return _isController[addr]; } /// @notice Set the `addr` controller status to `status`. function _setController(address addr, bool status) internal { _isController[addr] = status; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title ERC721 /// @author naomsa <https://twitter.com/naomsa666> /// @notice A complete ERC721 implementation including metadata and enumerable /// functions. Completely gas optimized and extensible. abstract contract ERC721 is IERC165, IERC721, IERC721Metadata, IERC721Enumerable { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'__` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice See {ERC721Metadata-name}. string public name; /// @notice See {ERC721Metadata-symbol}. string public symbol; /// @notice See {ERC721Enumerable-totalSupply}. uint256 public totalSupply; /// @notice Array of all owners. mapping(uint256 => address) private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token Id to it's approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ /// @dev Set token's name and symbol. constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {ERC721-balanceOf}. function balanceOf(address account_) public view virtual returns (uint256) { require(account_ != address(0), "ERC721: balance query for the zero address"); return _balanceOf[account_]; } /// @notice See {ERC721-ownerOf}. function ownerOf(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return owner; } /// @notice See {ERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {ERC721-approve}. function approve(address to_, uint256 tokenId_) public virtual { address owner = ownerOf(tokenId_); require(to_ != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to_, tokenId_); } /// @notice See {ERC721-getApproved}. function getApproved(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId_]; } /// @notice See {ERC721-setApprovalForAll}. function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } /// @notice See {ERC721-isApprovedForAll}. function isApprovedForAll(address account_, address operator_) public view virtual returns (bool) { return _isApprovedForAll[account_][operator_]; } /// @notice See {ERC721-transferFrom}. function transferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _transfer(from_, to_, tokenId_); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from_, to_, tokenId_, data_); } /// @notice See {ERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address account_, uint256 index_) public view returns (uint256 tokenId) { require(index_ < balanceOf(account_), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < totalSupply; ++i) { if (account_ == _owners[i]) { if (count == index_) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {ERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index_) public view virtual returns (uint256) { require(index_ < totalSupply, "ERC721Enumerable: Index out of bounds"); return index_; } /// @notice Returns a list of all token Ids owned by `owner`. function walletOfOwner(address account_) public view returns (uint256[] memory) { uint256 balance = balanceOf(account_); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) ids[i] = tokenOfOwnerByIndex(account_, i); return ids; } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'__` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /// @notice Safely transfers `tokenId_` token from `from_` to `to`, checking first that contract recipients /// are aware of the ERC721 protocol to prevent tokens from being forever locked. function _safeTransfer( address from_, address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _transfer(from_, to_, tokenId_); _checkOnERC721Received(from_, to_, tokenId_, data_); } /// @notice Returns whether `tokenId_` exists. function _exists(uint256 tokenId_) internal view virtual returns (bool) { return tokenId_ < totalSupply && _owners[tokenId_] != address(0); } /// @notice Returns whether `spender_` is allowed to manage `tokenId`. function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return (spender_ == owner || getApproved(tokenId_) == spender_ || isApprovedForAll(owner, spender_)); } /// @notice Safely mints `tokenId_` and transfers it to `to`. function _safeMint(address to_, uint256 tokenId_) internal virtual { _safeMint(to_, tokenId_, ""); } /// @notice Same as {_safeMint}, but with an additional `data_` parameter which is /// forwarded in {ERC721Receiver-onERC721Received} to contract recipients. function _safeMint( address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _mint(to_, tokenId_); _checkOnERC721Received(address(0), to_, tokenId_, data_); } /// @notice Mints `tokenId_` and transfers it to `to_`. function _mint(address to_, uint256 tokenId_) internal virtual { require(!_exists(tokenId_), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to_, tokenId_); _owners[tokenId_] = to_; totalSupply++; unchecked { _balanceOf[to_]++; } emit Transfer(address(0), to_, tokenId_); _afterTokenTransfer(address(0), to_, tokenId_); } /// @notice Destroys `tokenId`. The approval is cleared when the token is burned. function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); totalSupply--; _balanceOf[owner]--; delete _owners[tokenId_]; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); } /// @notice Transfers `tokenId_` from `from_` to `to`. function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual { require(_owners[tokenId_] == from_, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from_, to_, tokenId_); // Clear approvals from the previous owner _approve(address(0), tokenId_); _owners[tokenId_] = to_; unchecked { _balanceOf[from_]--; _balanceOf[to_]++; } emit Transfer(from_, to_, tokenId_); _afterTokenTransfer(from_, to_, tokenId_); } /// @notice Approve `to_` to operate on `tokenId_` function _approve(address to_, uint256 tokenId_) internal virtual { _tokenApprovals[tokenId_] = to_; emit Approval(_owners[tokenId_], to_, tokenId_); } /// @notice Approve `operator_` to operate on all of `account_` tokens. function _setApprovalForAll( address account_, address operator_, bool approved_ ) internal virtual { require(account_ != operator_, "ERC721: approve to caller"); _isApprovedForAll[account_][operator_] = approved_; emit ApprovalForAll(account_, operator_, approved_); } /// @notice ERC721Receiver callback checking and calling helper. function _checkOnERC721Received( address from_, address to_, uint256 tokenId_, bytes memory data_ ) private { if (to_.code.length > 0) { try IERC721Receiver(to_).onERC721Received(msg.sender, from_, tokenId_, data_) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /// @notice Hook that is called before any token transfer. function _beforeTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice Hook that is called after any token transfer. function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /* ___ _ _ _ _ __ _ __ */ /* /',__)( ) ( )( '_`\ /'__`\( '__) */ /* \__, \| (_) || (_) )( ___/| | */ /* (____/`\___/'| ,__/'`\____)(_) */ /* | | */ /* (_) */ /// @notice See {ERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId_) public view virtual returns (bool) { return interfaceId_ == type(IERC721).interfaceId || // ERC721 interfaceId_ == type(IERC721Metadata).interfaceId || // ERC721Metadata interfaceId_ == type(IERC721Enumerable).interfaceId || // ERC721Enumerable interfaceId_ == type(IERC165).interfaceId; // ERC165 } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; /** * @title ERC20 * @author naomsa <https://twitter.com/naomsa666> * @notice A complete ERC20 implementation including EIP-2612 permit feature. * Inspired by Solmate's ERC20, aiming at efficiency. */ abstract contract ERC20 is IERC20 { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice See {ERC20-name}. string public name; /// @notice See {ERC20-symbol}. string public symbol; /// @notice See {ERC20-decimals}. uint8 public immutable decimals; /// @notice Used to hash the Domain Separator. string public version; /// @notice See {ERC20-totalSupply}. uint256 public totalSupply; /// @notice See {ERC20-balanceOf}. mapping(address => uint256) public balanceOf; /// @notice See {ERC20-allowance}. mapping(address => mapping(address => uint256)) public allowance; /// @notice See {ERC2612-nonces}. mapping(address => uint256) public nonces; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ constructor( string memory name_, string memory symbol_, uint8 decimals_, string memory version_ ) { name = name_; symbol = symbol_; decimals = decimals_; version = version_; } /// @notice See {ERC20-transfer}. function transfer(address to_, uint256 value_) public returns (bool) { _transfer(msg.sender, to_, value_); return true; } /// @notice See {ERC20-transferFrom}. function transferFrom( address from_, address to_, uint256 value_ ) public returns (bool) { uint256 allowed = allowance[from_][msg.sender]; require(allowed >= value_, "ERC20: allowance exceeds transfer value"); if (allowed != type(uint256).max) allowance[from_][msg.sender] -= value_; _transfer(from_, to_, value_); return true; } /// @notice See {ERC20-approve}. function approve(address spender_, uint256 value_) public returns (bool) { _approve(msg.sender, spender_, value_); return true; } /// @notice See {ERC2612-DOMAIN_SEPARATOR}. function DOMAIN_SEPARATOR() public view returns (bytes32) { return _hashEIP712Domain(name, version, block.chainid, address(this)); } /// @notice See {ERC2612-permit}. function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) public { require(deadline_ >= block.timestamp, "ERC20: expired permit deadline"); // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 digest = _hashEIP712Message( DOMAIN_SEPARATOR(), keccak256( abi.encode( 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9, owner_, spender_, value_, nonces[owner_]++, deadline_ ) ) ); address signer = ecrecover(digest, v_, r_, s_); require(signer != address(0) && signer == owner_, "ERC20: invalid signature"); _approve(owner_, spender_, value_); } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'_` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /// @notice Internal transfer helper. Throws if `value_` exceeds `from_` balance. function _transfer( address from_, address to_, uint256 value_ ) internal { require(balanceOf[from_] >= value_, "ERC20: insufficient balance"); _beforeTokenTransfer(from_, to_, value_); unchecked { balanceOf[from_] -= value_; balanceOf[to_] += value_; } emit Transfer(from_, to_, value_); _afterTokenTransfer(from_, to_, value_); } /// @notice Internal approve helper. function _approve( address owner_, address spender_, uint256 value_ ) internal { allowance[owner_][spender_] = value_; emit Approval(owner_, spender_, value_); } /// @notice Internal minting logic. function _mint(address to_, uint256 value_) internal { _beforeTokenTransfer(address(0), to_, value_); totalSupply += value_; unchecked { balanceOf[to_] += value_; } emit Transfer(address(0), to_, value_); _afterTokenTransfer(address(0), to_, value_); } /// @notice Internal burning logic. function _burn(address from_, uint256 value_) internal { _beforeTokenTransfer(from_, address(0), value_); require(balanceOf[from_] >= value_, "ERC20: burn value exceeds balance"); unchecked { balanceOf[from_] -= value_; totalSupply -= value_; } emit Transfer(from_, address(0), value_); _afterTokenTransfer(from_, address(0), value_); } /** * @notice EIP721 domain hashing helper. * @dev Modified from https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol */ function _hashEIP712Domain( string memory name_, string memory version_, uint256 chainId_, address verifyingContract_ ) private pure returns (bytes32) { bytes32 result; assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name_, 32), mload(name_)) let versionHash := keccak256(add(version_, 32), mload(version_)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId_) mstore(add(memPtr, 128), verifyingContract_) // Compute hash result := keccak256(memPtr, 160) } return result; } /** * @notice EIP721 typed message hashing helper. * @dev Modified from https://github.com/0xProject/0x-monorepo/blob/development/contracts/utils/contracts/src/LibEIP712.sol */ function _hashEIP712Message(bytes32 domainSeparator_, bytes32 hash_) private pure returns (bytes32) { bytes32 result; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator_) // EIP712 domain hash mstore(add(memPtr, 34), hash_) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } function _beforeTokenTransfer( address from, address to, uint256 value ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 value ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
@notice Mints `tokenId_` and transfers it to `to_`.
function _mint(address to_, uint256 tokenId_) internal virtual { require(!_exists(tokenId_), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to_, tokenId_); _owners[tokenId_] = to_; totalSupply++; unchecked { _balanceOf[to_]++; } emit Transfer(address(0), to_, tokenId_); _afterTokenTransfer(address(0), to_, tokenId_); }
13,632,922
[ 1, 49, 28142, 1375, 2316, 548, 67, 68, 471, 29375, 518, 358, 1375, 869, 67, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 81, 474, 12, 2867, 358, 67, 16, 2254, 5034, 1147, 548, 67, 13, 2713, 5024, 288, 203, 565, 2583, 12, 5, 67, 1808, 12, 2316, 548, 67, 3631, 315, 654, 39, 27, 5340, 30, 1147, 1818, 312, 474, 329, 8863, 203, 203, 565, 389, 5771, 1345, 5912, 12, 2867, 12, 20, 3631, 358, 67, 16, 1147, 548, 67, 1769, 203, 203, 565, 389, 995, 414, 63, 2316, 548, 67, 65, 273, 358, 67, 31, 203, 565, 2078, 3088, 1283, 9904, 31, 203, 565, 22893, 288, 203, 1377, 389, 12296, 951, 63, 869, 67, 3737, 15, 31, 203, 565, 289, 203, 203, 565, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 67, 16, 1147, 548, 67, 1769, 203, 565, 389, 5205, 1345, 5912, 12, 2867, 12, 20, 3631, 358, 67, 16, 1147, 548, 67, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Certik DCK-01 import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Refer to Pancake SmartChef Contract: https://bscscan.com/address/0xCc2D359c3a99d9cfe8e6F31230142efF1C828e6D#readContract contract GameSlot is Ownable, ReentrancyGuard, IERC721Receiver { using SafeMath for uint256; using SafeBEP20 for IBEP20; IBEP20 public nativeToken; IBEP20 public gamePointToken; // The address of the manager address public SLOT_MANAGER; // Whether it is initialized bool public isInitialized; // The reserved tokens in the slot uint256 public reservedAmount; uint256 public unlockLimit; // GSD-03 uint256 public constant MAX_PERFORMANCE_FEE = 5000; // 50% uint256 public performanceFee = 200; // 2% // Whether it is suspended bool public suspended = false; uint256 public tokenId; address public ownerAccount; address public admin; IERC721 public NFT; // The NFT token address that each game provider should hold // address public treasury; address public treasury; // Send funds to blacklisted addresses are not allowed mapping(address => bool) public blacklistAddresses; event AdminTokenRecovery(address indexed tokenRecovered, uint256 amount); // Certik GSD-01 event EmergencyWithdraw(address indexed user, uint256 amount); event AddSlotEvent(uint256 indexed tokenId, address indexed gameAccount); event StatusChanged(address indexed slotAddress, bool suspended); event SlotUnlocked(address indexed user, address indexed gameAccount, uint256 amount); event AdminUpdated(address indexed user, address indexed admin); event Payout(address indexed user, address indexed receiver, uint256 amount); event CashoutPoints(address indexed user, uint256 amount); event AddToWhitelist(address indexed entry); event RemoveFromWhitelist(address indexed entry); event SetReservedAmount(uint256 amount); event SetPerformanceFee(uint256 amount); event SetUnlockLimitAmount(uint256 amount); event SetTreasury(address indexed amount); // Certik constructor( address _NFT, address _nativeToken, address _gamePointToken, uint256 _reservedAmount, address _manager ) public { require(_NFT != address(0), "_NFT is a zero address"); // Certik GSD-02 require(_nativeToken != address(0), "_nativeToken is a zero address"); require(_gamePointToken != address(0), "_gamePointToken is a zero address"); NFT = IERC721(_NFT); // Set manager to SlotManager rather than factory SLOT_MANAGER = _manager; nativeToken = IBEP20(_nativeToken); gamePointToken = IBEP20(_gamePointToken); reservedAmount = _reservedAmount; treasury = _manager; } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /* * @notice Initialize the contract, owner may not be the msg.sender * @param _tokenId: tokenId of the NFT * @param _owner: The current owner of NFT */ function initialize( uint256 _tokenId, address _owner ) external { require(!isInitialized, "Already initialized"); require(msg.sender == SLOT_MANAGER, "Not manager"); tokenId = _tokenId; _add(_tokenId, _owner); // Make this contract initialized isInitialized = true; emit AddSlotEvent(_tokenId, msg.sender); } /** * Game provider to bid slot * @param _owner is the NFT owner (Game provider) * @param _tokenId is the token owned by owner and to be transffered into this slot */ function _add(uint256 _tokenId, address _owner) private nonReentrant { require(NFT.ownerOf(_tokenId) != address(this), "Already owner"); NFT.safeTransferFrom( _owner, address(this), _tokenId ); // require(NFT.ownerOf(_tokenId) == address(this), "Not received"); // Certik GSD-09 ownerAccount = _owner; // Admin account is set to same account of ownerAccount first admin = _owner; } /** * @notice This function is private and not privilege checking * Safe token transfer function for nativeToken, just in case if rounding error causes pool to not have enough tokens. */ function safeTransfer(address _to, uint256 _amount) private { uint256 bal = nativeToken.balanceOf(address(this)); if (_amount > bal) { nativeToken.safeTransfer(_to, bal); // Certik GSD-07 } else { nativeToken.safeTransfer(_to, _amount); // Certik GSD-07 } } /** * @notice This function is private and not privilege checking * Safe token transfer function for point token, just in case if rounding error causes pool to not have enough tokens. */ function safeTransferPoints(address _to, uint256 _amount) private { uint256 bal = gamePointToken.balanceOf(address(this)); if (_amount > bal) { gamePointToken.safeTransfer(_to, bal); // Certik GSD-07 } else { gamePointToken.safeTransfer(_to, _amount); // Certik GSD-07 } } // Owner is the GameSlot, and triggered by Game Slot owner / admin function payout(address _to, uint256 _amount) external nonReentrant { require(_to != address(0), "Cannot send to 0 address"); require(_amount > 0, "Must more than 0"); require(!suspended, "Slot is suspended"); require(msg.sender == admin, "Only the game admin can payout"); require(_balance() > reservedAmount, "Balance must more than reserved"); require(_amount <= (_balance() - reservedAmount), "Exceeded max payout-able amount"); require(!blacklistAddresses[_to], "user is blacklisted"); uint256 currentPerformanceFee = _amount.mul(performanceFee).div(10000); safeTransfer(treasury, currentPerformanceFee); safeTransfer(_to, _amount.sub(currentPerformanceFee)); emit Payout(msg.sender, _to, _amount); } /** * @notice Owner is the GameSlot, and triggered by Game Slot owner * There is no theshold to cashout */ function cashoutPoints(uint256 _amount) external nonReentrant { require(_amount > 0, "Must more than 0"); require(!suspended, "Slot is suspended"); require(msg.sender == admin || msg.sender == ownerAccount, "Only the game owner or admin can cashout"); require(_amount <= _balanceOfPoints(), "Exceeded max game points amount"); safeTransferPoints(ownerAccount, _amount); emit CashoutPoints(msg.sender, _amount); } /** * Unlock NFT and return the slot back * Only return the current tokenId back to ownerAccount * * TODO: need more rules to unlock slot */ function unlock() external onlyOwner { require(_balance() < unlockLimit, "Balance must be less than balance before unlock"); // Certik GSD-03 NFT.transferFrom( address(this), ownerAccount, tokenId ); isInitialized = false; emit SlotUnlocked(msg.sender, ownerAccount, tokenId); } function addToBlacklist(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "NULL_ADDRESS"); blacklistAddresses[entry] = true; emit AddToWhitelist(entry); } } function removeFromBlacklist(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "NULL_ADDRESS"); blacklistAddresses[entry] = false; emit RemoveFromWhitelist(entry); } } /* * @notice Withdraw staked tokens without caring other factor * The funds will be sent to treasury, and the team need to manually refund back to users affected * * @dev TODO: Needs to be for emergency. */ function emergencyWithdraw() external onlyOwner { uint256 balance = _balance(); nativeToken.safeTransfer(treasury, balance); emit EmergencyWithdraw(msg.sender, balance); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(nativeToken), "Cannot be native token"); require(_tokenAddress != address(gamePointToken), "Cannot be point token"); IBEP20(_tokenAddress).safeTransfer(treasury, _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /** * @notice Sets Reserved Amount of native token * Can be zero only if the owner want to leave the slot * * @dev Only callable by the contract admin. */ function setAdmin(address _admin) external { require(_admin != address(0), "Address cannot be 0"); require(msg.sender == ownerAccount, "Only the game owener can update admin"); admin = _admin; emit AdminUpdated(msg.sender, _admin); } /** * @notice Sets Reserved Amount of native token * Can be zero only if the owner want to leave the slot * * @dev Only callable by the contract admin. */ function setReservedAmount(uint256 _reservedAmount) external onlyOwner { reservedAmount = _reservedAmount; emit SetReservedAmount(reservedAmount); } /** * @notice Only if unlockLimit is set and the balance is less than unlockLimit * Then it's able to unlock */ function setUnlockLimitAmount(uint256 _unlockLimit) external onlyOwner { unlockLimit = _unlockLimit; emit SetUnlockLimitAmount(_unlockLimit); } /** * @notice Sets performance fee * @dev Only callable by the contract admin. */ function setPerformanceFee(uint256 _performanceFee) external onlyOwner { require(_performanceFee <= MAX_PERFORMANCE_FEE, "performanceFee cannot be more than MAX_PERFORMANCE_FEE"); performanceFee = _performanceFee; emit SetPerformanceFee(performanceFee); } /** * @notice Sets treasury address * @dev Only callable by the contract owner. */ function setTreasury(address _treasury) external onlyOwner { require(_treasury != address(0), "Cannot be zero address"); treasury = _treasury; emit SetTreasury(treasury); } /** * @notice Sets treasury address * @dev Only callable by the contract owner. */ function flipSuspendState() external onlyOwner { suspended = !suspended; emit StatusChanged(msg.sender, suspended); } /** View functions */ function initialized() external view returns (bool) { return isInitialized; } function isSuspended() external view returns (bool) { return suspended; } function balanceOfPoints() external view returns (uint256) { return _balanceOfPoints(); } function _balanceOfPoints() private view returns (uint256) { return gamePointToken.balanceOf(address(this)); } function balance() external view returns (uint256) { return _balance(); } function _balance() private view returns (uint256) { return nativeToken.balanceOf(address(this)); } }
* @notice Sets performance fee @dev Only callable by the contract admin./
function setPerformanceFee(uint256 _performanceFee) external onlyOwner { require(_performanceFee <= MAX_PERFORMANCE_FEE, "performanceFee cannot be more than MAX_PERFORMANCE_FEE"); performanceFee = _performanceFee; emit SetPerformanceFee(performanceFee); }
929,693
[ 1, 2785, 9239, 14036, 225, 5098, 4140, 635, 326, 6835, 3981, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 25024, 14667, 12, 11890, 5034, 389, 16092, 1359, 14667, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 16092, 1359, 14667, 1648, 4552, 67, 3194, 4983, 4722, 67, 8090, 41, 16, 315, 16092, 1359, 14667, 2780, 506, 1898, 2353, 4552, 67, 3194, 4983, 4722, 67, 8090, 41, 8863, 203, 3639, 9239, 14667, 273, 389, 16092, 1359, 14667, 31, 203, 3639, 3626, 1000, 25024, 14667, 12, 16092, 1359, 14667, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.6; pragma abicoder v2; import { TokenInterface} from "../../../common/interfaces.sol"; import { DSMath } from "../../../common/math.sol"; import { Basic } from "../../../common/basic.sol"; import "./interface.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; abstract contract Helpers is DSMath, Basic { /** * @dev uniswap v3 NFT Position Manager & Swap Router */ INonfungiblePositionManager constant nftManager = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); ISwapRouter constant swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); struct MintParams { address tokenA; address tokenB; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amtA; uint256 amtB; uint256 slippage; } /** * @dev Get Last NFT Index * @param user: User address */ function _getLastNftId(address user) internal view returns (uint256 tokenId) { uint256 len = nftManager.balanceOf(user); tokenId = nftManager.tokenOfOwnerByIndex(user, len - 1); } function getMinAmount( TokenInterface token, uint256 amt, uint256 slippage ) internal view returns (uint256 minAmt) { uint256 _amt18 = convertTo18(token.decimals(), amt); minAmt = wmul(_amt18, sub(WAD, slippage)); minAmt = convert18ToDec(token.decimals(), minAmt); } function sortTokenAddress(address _token0, address _token1) internal view returns (address token0, address token1) { if (_token0 > _token1) { (token0, token1) = (_token1, _token0); } else { (token0, token1) = (_token0, _token1); } } function _createAndInitializePoolIfNecessary ( address tokenA, address tokenB, uint24 fee, int24 initialTick ) internal returns (address pool) { (TokenInterface token0Contract_, TokenInterface token1Contract_) = changeMaticAddress( tokenA, tokenB ); (address token0_, address token1_) = sortTokenAddress(address(token0Contract_), address(token1Contract_)); return nftManager.createAndInitializePoolIfNecessary( token0_, token1_, fee, TickMath.getSqrtRatioAtTick(initialTick) ); } /** * @dev Mint function which interact with Uniswap v3 */ function _mint(MintParams memory params) internal returns ( uint256 tokenId, uint128 liquidity, uint256 amountA, uint256 amountB ) { (TokenInterface _token0, TokenInterface _token1) = changeMaticAddress( params.tokenA, params.tokenB ); uint256 _amount0 = params.amtA == uint256(-1) ? getTokenBal(TokenInterface(params.tokenA)) : params.amtA; uint256 _amount1 = params.amtB == uint256(-1) ? getTokenBal(TokenInterface(params.tokenB)) : params.amtB; convertMaticToWmatic(address(_token0) == wmaticAddr, _token0, _amount0); convertMaticToWmatic(address(_token1) == wmaticAddr, _token1, _amount1); approve(_token0, address(nftManager), _amount0); approve(_token1, address(nftManager), _amount1); { (address token0, ) = sortTokenAddress( address(_token0), address(_token1) ); if (token0 != address(_token0)) { (_token0, _token1) = (_token1, _token0); (_amount0, _amount1) = (_amount1, _amount0); } } uint256 _minAmt0 = getMinAmount(_token0, _amount0, params.slippage); uint256 _minAmt1 = getMinAmount(_token1, _amount1, params.slippage); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( address(_token0), address(_token1), params.fee, params.tickLower, params.tickUpper, _amount0, _amount1, _minAmt0, _minAmt1, address(this), block.timestamp ); (tokenId, liquidity, amountA, amountB) = nftManager.mint(params); } function getNftTokenPairAddresses(uint256 _tokenId) internal view returns (address token0, address token1) { (bool success, bytes memory data) = address(nftManager).staticcall( abi.encodeWithSelector(nftManager.positions.selector, _tokenId) ); require(success, "fetching positions failed"); { (, , token0, token1, , , , ) = abi.decode( data, ( uint96, address, address, address, uint24, int24, int24, uint128 ) ); } } /** * @dev Check if token address is maticAddr and convert it to wmatic */ function _checkMATIC( address _token0, address _token1, uint256 _amount0, uint256 _amount1 ) internal { bool isMatic0 = _token0 == wmaticAddr; bool isMatic1 = _token1 == wmaticAddr; convertMaticToWmatic(isMatic0, TokenInterface(_token0), _amount0); convertMaticToWmatic(isMatic1, TokenInterface(_token1), _amount1); approve(TokenInterface(_token0), address(nftManager), _amount0); approve(TokenInterface(_token1), address(nftManager), _amount1); } /** * @dev addLiquidityWrapper function wrapper of _addLiquidity */ function _addLiquidityWrapper( uint256 tokenId, uint256 amountA, uint256 amountB, uint256 slippage ) internal returns ( uint256 liquidity, uint256 amtA, uint256 amtB ) { (address token0, address token1) = getNftTokenPairAddresses(tokenId); (liquidity, amtA, amtB) = _addLiquidity( tokenId, token0, token1, amountA, amountB, slippage ); } /** * @dev addLiquidity function which interact with Uniswap v3 */ function _addLiquidity( uint256 _tokenId, address _token0, address _token1, uint256 _amount0, uint256 _amount1, uint256 _slippage ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { _checkMATIC(_token0, _token1, _amount0, _amount1); uint256 _amount0Min = getMinAmount( TokenInterface(_token0), _amount0, _slippage ); uint256 _amount1Min = getMinAmount( TokenInterface(_token1), _amount1, _slippage ); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager.IncreaseLiquidityParams( _tokenId, _amount0, _amount1, _amount0Min, _amount1Min, block.timestamp ); (liquidity, amount0, amount1) = nftManager.increaseLiquidity(params); } /** * @dev decreaseLiquidity function which interact with Uniswap v3 */ function _decreaseLiquidity( uint256 _tokenId, uint128 _liquidity, uint256 _amount0Min, uint256 _amount1Min ) internal returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager.DecreaseLiquidityParams( _tokenId, _liquidity, _amount0Min, _amount1Min, block.timestamp ); (amount0, amount1) = nftManager.decreaseLiquidity(params); } /** * @dev collect function which interact with Uniswap v3 */ function _collect( uint256 _tokenId, uint128 _amount0Max, uint128 _amount1Max ) internal returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams( _tokenId, address(this), _amount0Max, _amount1Max ); (amount0, amount1) = nftManager.collect(params); } /** * @dev Burn Function */ function _burn(uint256 _tokenId) internal { nftManager.burn(_tokenId); } }
* @dev addLiquidity function which interact with Uniswap v3/
function _addLiquidity( uint256 _tokenId, address _token0, address _token1, uint256 _amount0, uint256 _amount1, uint256 _slippage ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { _checkMATIC(_token0, _token1, _amount0, _amount1); uint256 _amount0Min = getMinAmount( TokenInterface(_token0), _amount0, _slippage ); uint256 _amount1Min = getMinAmount( TokenInterface(_token1), _amount1, _slippage ); INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager.IncreaseLiquidityParams( _tokenId, _amount0, _amount1, _amount0Min, _amount1Min, block.timestamp ); (liquidity, amount0, amount1) = nftManager.increaseLiquidity(params); }
5,525,609
[ 1, 1289, 48, 18988, 24237, 445, 1492, 16592, 598, 1351, 291, 91, 438, 331, 23, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1289, 48, 18988, 24237, 12, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 1758, 389, 2316, 20, 16, 203, 3639, 1758, 389, 2316, 21, 16, 203, 3639, 2254, 5034, 389, 8949, 20, 16, 203, 3639, 2254, 5034, 389, 8949, 21, 16, 203, 3639, 2254, 5034, 389, 87, 3169, 2433, 203, 565, 262, 203, 3639, 2713, 203, 3639, 1135, 261, 203, 5411, 2254, 10392, 4501, 372, 24237, 16, 203, 5411, 2254, 5034, 3844, 20, 16, 203, 5411, 2254, 5034, 3844, 21, 203, 3639, 262, 203, 565, 288, 203, 3639, 389, 1893, 49, 11781, 24899, 2316, 20, 16, 389, 2316, 21, 16, 389, 8949, 20, 16, 389, 8949, 21, 1769, 203, 3639, 2254, 5034, 389, 8949, 20, 2930, 273, 9555, 6275, 12, 203, 5411, 29938, 24899, 2316, 20, 3631, 203, 5411, 389, 8949, 20, 16, 203, 5411, 389, 87, 3169, 2433, 203, 3639, 11272, 203, 3639, 2254, 5034, 389, 8949, 21, 2930, 273, 9555, 6275, 12, 203, 5411, 29938, 24899, 2316, 21, 3631, 203, 5411, 389, 8949, 21, 16, 203, 5411, 389, 87, 3169, 2433, 203, 3639, 11272, 203, 3639, 2120, 265, 12125, 75, 1523, 2555, 1318, 18, 382, 11908, 48, 18988, 24237, 1370, 203, 5411, 3778, 859, 273, 2120, 265, 12125, 75, 1523, 2555, 1318, 18, 382, 11908, 48, 18988, 24237, 1370, 12, 203, 7734, 389, 2316, 548, 16, 203, 7734, 389, 8949, 20, 16, 203, 7734, 389, 8949, 21, 16, 203, 7734, 389, 8949, 20, 2930, 16, 203, 7734, 389, 8949, 21, 2930, 16, 203, 7734, 1203, 18, 5508, 2 ]
./partial_match/42/0xe386975DA28f4afe52A52DD134e429B1647DbCF3/sources/Vault.sol
* @dev See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for `sender`'s tokens of at least `amount`./
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20:1")); return true; }
3,399,260
[ 1, 9704, 288, 45, 654, 39, 3462, 17, 13866, 1265, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 1220, 353, 486, 1931, 635, 326, 512, 2579, 18, 2164, 326, 4721, 622, 326, 8435, 434, 288, 654, 39, 3462, 20451, 29076, 30, 300, 1375, 15330, 68, 471, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 300, 326, 4894, 1297, 1240, 1699, 1359, 364, 1375, 15330, 11294, 87, 2430, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 389, 12908, 537, 12, 15330, 16, 389, 3576, 12021, 9334, 389, 5965, 6872, 63, 15330, 6362, 67, 3576, 12021, 1435, 8009, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 21, 7923, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x42B3879E99650668EBAc71f02a7BEb768633d096/sources/project_/contracts/XToken-Lite.sol
Mapping of addresses and their respective token release date
mapping(address => uint256) private _transferLocks;
11,630,015
[ 1, 3233, 434, 6138, 471, 3675, 17613, 1147, 3992, 1509, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 13866, 19159, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x68208427c85a76b1F53349519D411d16DAa708a8/sources/FundManageCall.sol
* 设置开仓 lockUp必须为true _asset 当前合约资产价值多少USDC--带小数/
function enableOpenUp(uint _totalAsset) external onlyOwner returns (bool) { return IFundManage(FUND_MANAGE).enableOpenUp(_totalAsset); }
5,243,701
[ 1, 169, 111, 127, 168, 126, 111, 166, 125, 227, 165, 124, 246, 225, 2176, 1211, 166, 128, 232, 170, 99, 124, 165, 121, 123, 3767, 389, 9406, 225, 166, 126, 246, 166, 236, 240, 166, 243, 235, 168, 123, 104, 169, 118, 231, 165, 123, 105, 165, 124, 120, 166, 227, 125, 166, 102, 253, 166, 113, 244, 3378, 5528, 413, 166, 121, 104, 166, 113, 242, 167, 248, 113, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4237, 3678, 1211, 12, 11890, 389, 4963, 6672, 13, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 327, 11083, 1074, 21258, 12, 42, 5240, 67, 9560, 2833, 2934, 7589, 3678, 1211, 24899, 4963, 6672, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-02-23 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: Babylonian // import "@uniswap/lib/contracts/libraries/Babylonian.sol"; library Babylonian { function sqrt(int256 y) internal pure returns (int256 z) { if (y > 3) { z = y; int256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // Part: IPickleJar interface IPickleJar { function balanceOf(address account) external view returns (uint256); function depositAll() external; function deposit(uint256 _amount) external; } // Part: IUniswapV2Pair interface IUniswapV2Pair { function getReserves() external view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 { modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } // **** ADD LIQUIDITY **** function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); } // Part: IveCurveVault interface IveCurveVault { function depositAll() external; function deposit(uint256 _amount) external; function approve(address spender, uint256 amount) external returns (bool); function transfer(address dst, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: OpenZeppelin/[email protected]/SignedSafeMath /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Part: OpenZeppelin/[email protected]/Ownable /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // File: ZapYveCrvEthLPsToPickle.sol contract ZapYveCrvEthLPsToPickle is Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using SignedSafeMath for int256; // Tokens address public constant ethYveCrv = 0x10B47177E92Ef9D5C6059055d92DdF6290848991; // LP Token address public constant yveCrv = 0xc5bDdf9843308380375a611c18B50Fb9341f502A; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IPickleJar public pickleJar = IPickleJar(0x5Eff6d166D66BacBC1BF52E2C54dD391AE6b1f48); IveCurveVault public yVault = IveCurveVault(yveCrv); // DEXes address public activeDex = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushi default address public sushiswapRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; IUniswapV2Router02 public swapRouter; // ETH/CRV pair we want to swap with address public swapPair = 0x58Dc5a51fE44589BEb22E8CE67720B5BC5378009; // Initialize with Sushiswap address public sushiswapPair = 0x58Dc5a51fE44589BEb22E8CE67720B5BC5378009; address public uniswapPair = 0x3dA1313aE46132A397D90d95B1424A9A7e3e0fCE; // Dex swap paths address[] public swapEthPath; address[] public swapCrvPath; address[] public swapForYveCrvPath; // Misc address payable public governance = 0xFEB4acf3df3cDEA7399794D0869ef76A6EfAff52; modifier onlyGovernance() { require(msg.sender == governance, "!authorized"); _; } constructor() public Ownable() { // Initialize with Sushiswap swapRouter = IUniswapV2Router02(activeDex); // Setup some initial approvals IERC20(crv).safeApprove(activeDex, uint256(-1)); // For curve swaps on dex IERC20(weth).safeApprove(activeDex, uint256(-1)); // For staking into pickle jar IERC20(crv).safeApprove(yveCrv, uint256(-1));// approve vault to take curve IERC20(yveCrv).safeApprove(sushiswapRouter, uint256(-1)); IERC20(ethYveCrv).safeApprove(address(pickleJar), uint256(-1)); // For staking into pickle jar swapEthPath = new address[](2); swapEthPath[0] = weth; swapEthPath[1] = crv; swapCrvPath = new address[](2); swapCrvPath[0] = crv; swapCrvPath[1] = weth; swapForYveCrvPath = new address[](2); swapForYveCrvPath[0] = weth; swapForYveCrvPath[1] = yveCrv; } function setGovernance(address payable _governance) external onlyGovernance { governance = _governance; } /* ETH Zap */ function zapInETH() external payable { _zapIn(true, msg.value); } /* CRV Zap (denominated in wei) */ function zapInCRV(uint256 crvAmount) external { require(crvAmount != 0, "0 CRV"); IERC20(crv).transferFrom(msg.sender, address(this), crvAmount); _zapIn(false, IERC20(crv).balanceOf(address(this))); // Include any dust from prev txns } function _zapIn(bool _isEth, uint256 _haveAmount) internal returns (uint256) { IUniswapV2Pair lpPair = IUniswapV2Pair(ethYveCrv); // Pair we LP against (uint112 lpReserveA, uint112 lpReserveB, ) = lpPair.getReserves(); // Check if it's worthwhile to use the Yearn yveCRV vault bool useVault = shouldUseVault(lpReserveA, lpReserveB); // Logic tree below is used to calculate amounts and then swap based on useVault and Zap token type if(useVault){ // Calculate swap amount uint256 amountToSwap = calculateSwapAmount(_isEth, _haveAmount); _tokenSwap(_isEth, amountToSwap); yVault.depositAll(); } else{ if(_isEth){ // Calculate the swap needed for the right amount of yveCRV for a single-sided deposit int256 amountToSell = calculateSingleSided(lpReserveA, address(this).balance); swapRouter.swapExactETHForTokens{value: uint256(amountToSell)}(1, swapForYveCrvPath, address(this), now); } else{ // User sent CRV: Must convert all CRV to WETH first, not ETH - this will save some gas when LP'ing uint amountWeth = IUniswapV2Router02(sushiswapRouter).swapExactTokensForTokens(_haveAmount, 0, swapCrvPath, address(this), now)[swapCrvPath.length - 1]; int256 amountToSell = calculateSingleSided(lpReserveA, amountWeth); swapRouter.swapExactTokensForTokens(uint256(amountToSell), 1, swapForYveCrvPath, address(this), now); } } // Add liquidity based on whether we're holding ETH or WETH if(_isEth){ IUniswapV2Router02(sushiswapRouter).addLiquidityETH{value: address(this).balance}( yveCrv, yVault.balanceOf(address(this)), 1, 1, address(this), now ); } else{ // To save gas, CRV handles only weth, so we use a different function to add liquidity when holding weth IUniswapV2Router02(sushiswapRouter).addLiquidity( yveCrv, weth, yVault.balanceOf(address(this)), IERC20(weth).balanceOf(address(this)), 0, 0, address(this), now ); } // Deposit LP tokens to Pickle jar and send tokens back to user pickleJar.depositAll(); IERC20(address(pickleJar)).safeTransfer(msg.sender, pickleJar.balanceOf(address(this))); // This is where we would stake pickle jar tokens but unfortunately // the Pickle staking contract does not permit deposits // on behalf of another user / address // https://github.com/pickle-finance/protocol/blob/db62174dd0c95839057c91406ee361575530b359/src/yield-farming/masterchef.sol#L212 } function _tokenSwap(bool _isEth, uint256 _amountIn) internal returns (uint256) { uint256 amountOut = 0; if (_isEth) { amountOut = swapRouter.swapExactETHForTokens{value: _amountIn}(1, swapEthPath, address(this), now)[swapEthPath.length - 1]; } else { // Buy WETH, not ETH - this will save some gas when LP'ing amountOut = swapRouter.swapExactTokensForTokens(_amountIn, 0, swapCrvPath, address(this), now)[swapCrvPath.length - 1]; } require(amountOut > 0, "Error Swapping Tokens"); return amountOut; } function setActiveDex(uint256 exchange) public onlyGovernance { if(exchange == 0){ activeDex = sushiswapRouter; swapPair = sushiswapPair; }else if (exchange == 1) { activeDex = uniswapRouter; swapPair = uniswapPair; }else{ require(false, "incorrect pool"); } swapRouter = IUniswapV2Router02(activeDex); IERC20(crv).safeApprove(activeDex, uint256(-1)); IERC20(weth).safeApprove(activeDex, uint256(-1)); } function sweep(address _token) external onlyGovernance { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); uint256 balance = address(this).balance; if(balance > 0){ governance.transfer(balance); } } function shouldUseVault(uint256 lpReserveA, uint256 lpReserveB) internal view returns (bool) { uint256 safetyFactor = 1e5; // For extra precision // Get asset ratio of swap pair IUniswapV2Pair pair = IUniswapV2Pair(swapPair); // Pair we might want to swap against (uint256 reserveA, uint256 reserveB, ) = pair.getReserves(); uint256 pool1ratio = reserveB.mul(safetyFactor).div(reserveA); // Get asset ratio of LP pair uint256 pool2ratio = lpReserveB.mul(safetyFactor).div(lpReserveA); return pool1ratio > pool2ratio; // Use vault only if pool 2 offers a better price } function calculateSingleSided(uint256 reserveIn, uint256 userIn) internal pure returns (int256) { return Babylonian.sqrt( int256(reserveIn).mul(int256(userIn).mul(3988000) + int256(reserveIn).mul(3988009)) ).sub(int256(reserveIn).mul(1997)) / 1994; } // This function goes into some complex math which is explained here: // https://hackmd.io/@Ap_76vwNTg-vxJxbiaLMMQ/rkoFT_bz_ function calculateSwapAmount(bool _isEth, uint256 _haveAmount) internal view returns (uint256) { IUniswapV2Pair pair = IUniswapV2Pair(swapPair); // Pair we swap against (uint256 reserveA, uint256 reserveB, ) = pair.getReserves(); int256 pool1HaveReserve = 0; int256 pool1WantReserve = 0; int256 rb = 0; int256 ra = 0; if(_isEth){ pool1HaveReserve = int256(reserveA); pool1WantReserve = int256(reserveB); } else{ pool1HaveReserve = int256(reserveB); pool1WantReserve = int256(reserveA); } pair = IUniswapV2Pair(ethYveCrv); // Pair we swap against (reserveA, reserveB, ) = pair.getReserves(); if(_isEth){ ra = int256(reserveB); rb = int256(reserveA); } else{ ra = int256(reserveA); rb = int256(reserveB); } int256 numToSquare = int256(_haveAmount).mul(997); // This line and the next one add together a part of the formula... numToSquare = numToSquare.add(pool1HaveReserve.mul(1000)); // ...which we'll need to square later on. int256 FACTOR = 1e20; // To help with precision // LINE 1 int256 h = int256(_haveAmount); // re-assert this or else stack will get too deep and forget it int256 a = pool1WantReserve.mul(-1994).mul(ra).div(rb); int256 b = h.mul(997); b = b.sub(pool1HaveReserve.mul(1000)); b = a.mul(b); // LINE 2 a = ra.mul(ra).mul(FACTOR).div(rb); a = a.div(rb); // We lose some precision here int256 c = numToSquare.mul(numToSquare); a = c.mul(a).div(FACTOR); a = b.add(a); // Add result to total // LINE 3 int256 r = pool1WantReserve.mul(pool1WantReserve); r = r.mul(994009); a = a.add(r); // Add result to total // Sqaure what we have so far int256 sq = Babylonian.sqrt(a); // LINE 4 b = h.mul(997).mul(ra).mul(FACTOR).div(rb); // LINE 5 FACTOR = 1e20; // re-state, otherwise stack depth is exceeded r = pool1HaveReserve.mul(1000); r = r.mul(ra).mul(FACTOR); r = r.div(rb); h = pool1WantReserve.mul(-997); h = h.mul(FACTOR).sub(r); b = b.add(h).div(FACTOR); b = b.add(sq); // LINE 6 a = ra.mul(1994); a = a.mul(FACTOR).div(rb); // We lose some precision here return uint256(b.mul(FACTOR).div(a)); } receive() external payable { _zapIn(true, msg.value); } }
For staking into pickle jar
IERC20(ethYveCrv).safeApprove(address(pickleJar), uint256(-1));
15,065,822
[ 1, 1290, 384, 6159, 1368, 13379, 7334, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 654, 39, 3462, 12, 546, 61, 537, 39, 4962, 2934, 4626, 12053, 537, 12, 2867, 12, 20847, 10813, 3631, 2254, 5034, 19236, 21, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x7C2A9525818B0c1589885de370323B1B385224D1/sources/SmokleySLounge.sol
* public membership/
function getMembersToken() external nonReentrant { require(membershipIsActive, "membership closed"); require(!membership[msg.sender], "already have membership token"); uint256 tokenId = totalMembers; _safeMint(msg.sender, tokenId); totalMembers += 1; membership[msg.sender] = true; }
3,825,499
[ 1, 482, 12459, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 29106, 1345, 1435, 7010, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 2583, 12, 19679, 2520, 3896, 16, 315, 19679, 4375, 8863, 203, 3639, 2583, 12, 5, 19679, 63, 3576, 18, 15330, 6487, 315, 17583, 1240, 12459, 1147, 8863, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 2078, 6918, 31, 203, 203, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 1147, 548, 1769, 203, 540, 203, 3639, 2078, 6918, 1011, 404, 31, 203, 3639, 12459, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 203, 540, 203, 565, 289, 203, 203, 377, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xfE21B0A8dF3308c61CB13DF57ae5962c567A668A/sources/EphimeraToken.sol
solhint-disable-next-line no-inline-assembly
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!isContract(to)) { return true; } IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert("ERC721: transfer to non ERC721Receiver implementer"); } bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == ERC721_RECEIVED); } }
2,851,947
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 16, 1731, 3778, 389, 892, 13, 203, 565, 3238, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 309, 16051, 291, 8924, 12, 869, 3719, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 7734, 467, 654, 39, 27, 5340, 12952, 12, 869, 2934, 265, 654, 39, 27, 5340, 8872, 18, 9663, 16, 203, 7734, 389, 3576, 12021, 9334, 203, 7734, 628, 16, 203, 7734, 1147, 548, 16, 203, 7734, 389, 892, 203, 5411, 262, 1769, 203, 3639, 309, 16051, 4768, 13, 288, 203, 5411, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 203, 7734, 19931, 288, 203, 10792, 2231, 327, 892, 67, 1467, 519, 312, 945, 12, 2463, 892, 13, 203, 10792, 15226, 12, 1289, 12, 1578, 16, 327, 892, 3631, 327, 892, 67, 1467, 13, 203, 7734, 289, 203, 7734, 15226, 2932, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 8863, 203, 5411, 289, 203, 5411, 1731, 24, 5221, 273, 24126, 18, 3922, 12, 2463, 892, 16, 261, 3890, 24, 10019, 203, 5411, 327, 261, 18341, 422, 4232, 39, 27, 5340, 67, 27086, 20764, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } contract VariationInterface { function isVariation() public pure returns(bool); function createVariation(uint256 _gene, uint256 _totalSupply) public returns (uint8); function registerVariation(uint256 _dogId, address _owner) public; } contract LotteryInterface { function isLottery() public pure returns (bool); function checkLottery(uint256 genes) public pure returns (uint8 lotclass); function registerLottery(uint256 _dogId) public payable returns (uint8); function getCLottery() public view returns ( uint8[7] luckyGenes1, uint256 totalAmount1, uint256 openBlock1, bool isReward1, uint256 term1, uint8 currentGenes1, uint256 tSupply, uint256 sPoolAmount1, uint256[] reward1 ); } /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogAccessControl { // This facet controls access control for Cryptodogs. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 dogs to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn&#39;t have the ability to act in those roles. This // restriction is intentional so that we aren&#39;t tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require(msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } } /// @title Base contract for Cryptodogs. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogBase is DogAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously /// includes any time a cat is created through the giveBirth method, but it is also called /// when a new gen0 cat is created. event Birth(address owner, uint256 dogId, uint256 matronId, uint256 sireId, uint256 genes, uint16 generation, uint8 variation, uint256 gen0, uint256 birthTime, uint256 income, uint16 cooldownIndex); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Dog struct. Every cat in Cryptodogs is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Dog { // The Dog&#39;s genetic code is packed into these 256-bits, the format is // sooper-sekret! A cat&#39;s genes never change. uint256 genes; // The timestamp from the block when this cat came into existence. uint256 birthTime; // The minimum timestamp after which this cat can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Dog, set to 0 for gen0 cats. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion cats. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won&#39;t be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire cat for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a cat // is pregnant. Used to retrieve the genetic material for the new // kitten when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Dog. This starts at zero // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this cat is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this cat. Cats minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other cats is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; //zhangyong //变异系数 uint8 variation; //zhangyong //0代狗祖先 uint256 gen0; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a cat /// is bred, encouraging owners not to just keep breeding the same cat over /// and over again. Caps out at one week (a cat can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(24 hours), uint32(2 days), uint32(3 days), uint32(5 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Dog struct for all dogs in existence. The ID /// of each cat is actually an index into this array. Note that ID 0 is a negacat, /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, cat ID 0 is invalid... ;-) Dog[] dogs; /// @dev A mapping from cat IDs to the address that owns them. All cats have /// some valid owner address, even gen0 cats are created with a non-zero owner. mapping (uint256 => address) dogIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KittyIDs to an address that has been approved to call /// transferFrom(). Each Dog can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public dogIndexToApproved; /// @dev A mapping from KittyIDs to an address that has been approved to use /// this Dog for siring via breedWith(). Each Dog can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of dogs. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; uint256 public autoBirthFee = 5000 szabo; //zhangyong //0代狗获取的繁殖收益 uint256 public gen0Profit = 500 szabo; //zhangyong //0代狗获取繁殖收益的系数,可以动态调整,取值范围0到100 function setGen0Profit(uint256 _value) public onlyCOO{ uint256 ration = _value * 100 / autoBirthFee; require(ration > 0); require(_value <= 100); gen0Profit = _value; } /// @dev Assigns ownership of a specific Dog to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of kittens is capped to 2^32 we can&#39;t overflow this ownershipTokenCount[_to]++; // transfer ownership dogIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can&#39;t account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete dogIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new Dog and stores it. This /// method doesn&#39;t do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The Dog ID of the matron of this cat (zero for gen0) /// @param _sireId The Dog ID of the sire of this cat (zero for gen0) /// @param _generation The generation number of this cat, must be computed by caller. /// @param _genes The Dog&#39;s genetic code. /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) //zhangyong //增加变异系数与0代狗祖先作为参数 function _createDog( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner, uint8 _variation, uint256 _gen0, bool _isGen0Siring ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createDog() is already // an expensive call (for storage), and it doesn&#39;t hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New Dog starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Dog memory _dog = Dog({ genes: _genes, birthTime: block.number, cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation), variation : uint8(_variation), gen0 : _gen0 }); uint256 newDogId = dogs.push(_dog) - 1; // It&#39;s probably never going to happen, 4 billion cats is A LOT, but // let&#39;s just be 100% sure we never let this happen. // require(newDogId == uint256(uint32(newDogId))); require(newDogId < 23887872); // emit the birth event Birth( _owner, newDogId, uint256(_dog.matronId), uint256(_dog.sireId), _dog.genes, uint16(_generation), _variation, _gen0, block.number, _isGen0Siring ? 0 : gen0Profit, cooldownIndex ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newDogId); return newDogId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the dogs, /// it has one function that will return the data as bytes. // contract ERC721Metadata { // /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. // function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { // if (_tokenId == 1) { // buffer[0] = "Hello World! :D"; // count = 15; // } else if (_tokenId == 2) { // buffer[0] = "I would definitely choose a medi"; // buffer[1] = "um length string."; // count = 49; // } else if (_tokenId == 3) { // buffer[0] = "Lorem ipsum dolor sit amet, mi e"; // buffer[1] = "st accumsan dapibus augue lorem,"; // buffer[2] = " tristique vestibulum id, libero"; // buffer[3] = " suscipit varius sapien aliquam."; // count = 128; // } // } // } /// @title The facet of the Cryptodogs core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogOwnership is DogBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "HelloDog"; string public constant symbol = "HD"; // The contract that will return Dog metadata // ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")); // bytes4(keccak256("tokensOfOwner(address)")) ^ // bytes4(keccak256("tokenMetadata(uint256,string)")); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. // function setMetadataAddress(address _contractAddress) public onlyCEO { // erc721Metadata = ERC721Metadata(_contractAddress); // } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Dog. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return dogIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Dog. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return dogIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting dogs on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { dogIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of dogs owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Dog to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Cryptodogs specifically) or your Dog may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Dog to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any dogs (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of dogs // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Dog via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Dog that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Dog owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Dog to be transfered. /// @param _to The address that should take ownership of the Dog. Can be any address, /// including the caller. /// @param _tokenId The ID of the Dog to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any dogs (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of dogs currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return dogs.length - 1; } /// @notice Returns the address currently assigned ownership of a given Dog. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = dogIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Dog IDs assigned to an address. /// @param _owner The owner whose dogs we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire Dog array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. // function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { // uint256 tokenCount = balanceOf(_owner); // if (tokenCount == 0) { // // Return an empty array // return new uint256[](0); // } else { // uint256[] memory result = new uint256[](tokenCount); // uint256 totalCats = totalSupply(); // uint256 resultIndex = 0; // // We count on the fact that all cats have IDs starting at 1 and increasing // // sequentially up to the totalCat count. // uint256 catId; // for (catId = 1; catId <= totalCats; catId++) { // if (dogIndexToOwner[catId] == _owner) { // result[resultIndex] = catId; // resultIndex++; // } // } // return result; // } // } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol // function _memcpy(uint _dest, uint _src, uint _len) private view { // // Copy word-length chunks while possible // for(; _len >= 32; _len -= 32) { // assembly { // mstore(_dest, mload(_src)) // } // _dest += 32; // _src += 32; // } // // Copy remaining bytes // uint256 mask = 256 ** (32 - _len) - 1; // assembly { // let srcpart := and(mload(_src), not(mask)) // let destpart := and(mload(_dest), mask) // mstore(_dest, or(destpart, srcpart)) // } // } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol // function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { // var outputString = new string(_stringLength); // uint256 outputPtr; // uint256 bytesPtr; // assembly { // outputPtr := add(outputString, 32) // bytesPtr := _rawBytes // } // _memcpy(outputPtr, bytesPtr, _stringLength); // return outputString; // } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Dog whose metadata should be returned. // function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { // require(erc721Metadata != address(0)); // bytes32[4] memory buffer; // uint256 count; // (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); // return _toString(buffer, count); // } } /// @title A facet of KittyCore that manages Dog siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract DogBreeding is DogOwnership { /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 matronCooldownEndBlock, uint256 sireCooldownEndBlock, uint256 matronCooldownIndex, uint256 sireCooldownIndex); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. // uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant dogs. uint256 public pregnantDogs; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; VariationInterface public variation; LotteryInterface public lottery; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given kitten is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Dog _dog) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the cat has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_dog.siringWithId == 0) && (_dog.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron&#39;s owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = dogIndexToOwner[_matronId]; address sireOwner = dogIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron&#39;s owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Dog, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _dog A reference to the Dog in storage which needs its timer started. function _triggerCooldown(Dog storage _dog) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _dog.cooldownEndBlock = uint64((cooldowns[_dog.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_dog.cooldownIndex < 13) { _dog.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your dogs. /// @param _addr The address that will be able to sire with your Dog. Set to /// address(0) to clear all siring approvals for this Dog. /// @param _sireId A Dog that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { require(val > 0); autoBirthFee = val; } /// @dev Checks to see if a given Dog is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Dog _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _dogId reference the id of the kitten, any user can inquire about it function isReadyToBreed(uint256 _dogId) public view returns (bool) { //zhangyong //创世狗有两只 require(_dogId > 1); Dog storage dog = dogs[_dogId]; return _isReadyToBreed(dog); } /// @dev Checks whether a Dog is currently pregnant. /// @param _dogId reference the id of the kitten, any user can inquire about it function isPregnant(uint256 _dogId) public view returns (bool) { // A Dog is pregnant if and only if this field is set return dogs[_dogId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Dog struct of the potential matron. /// @param _matronId The matron&#39;s ID. /// @param _sire A reference to the Dog struct of the potential sire. /// @param _sireId The sire&#39;s ID function _isValidMatingPair( Dog storage _matron, uint256 _matronId, Dog storage _sire, uint256 _sireId ) private view returns(bool) { // A Dog can&#39;t breed with itself! if (_matronId == _sireId) { return false; } // dogs can&#39;t breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either cat is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // dogs can&#39;t breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let&#39;s get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Dog storage matron = dogs[_matronId]; Dog storage sire = dogs[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } // @notice Checks to see if two cats can breed together, including checks for // ownership and siring approvals. Does NOT check that both cats are ready for // breeding (i.e. breedWith could still fail until the cooldowns are finished). // TODO: Shouldn&#39;t this check pregnancy and cooldowns?!? // @param _matronId The ID of the proposed matron. // @param _sireId The ID of the proposed sire. // function canBreedWith(uint256 _matronId, uint256 _sireId) // external // view // returns(bool) // { // require(_matronId > 1); // require(_sireId > 1); // Dog storage matron = dogs[_matronId]; // Dog storage sire = dogs[_sireId]; // return _isValidMatingPair(matron, _matronId, sire, _sireId) && // _isSiringPermitted(_sireId, _matronId); // } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { //zhangyong //创世狗不能繁殖 require(_matronId > 1); require(_sireId > 1); // Grab a reference to the dogs from storage. Dog storage sire = dogs[_sireId]; Dog storage matron = dogs[_matronId]; //zhangyong //变异狗不能繁殖 require(sire.variation == 0); require(matron.variation == 0); if (matron.generation > 0) { var(,,openBlock,,,,,,) = lottery.getCLottery(); if (matron.birthTime < openBlock) { require(lottery.checkLottery(matron.genes) == 100); } } // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it&#39;s likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a Dog gets pregnant, counter is incremented. pregnantDogs++; //zhangyong //只能由系统接生,接生费转给公司作为开发费用 cfoAddress.transfer(autoBirthFee); //zhangyong //如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同 if (matron.generation > 0) { dogIndexToOwner[matron.gen0].transfer(gen0Profit); } // Emit the pregnancy event. Pregnant(dogIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock, sire.cooldownEndBlock, matron.cooldownIndex, sire.cooldownIndex); } /// @notice Breed a Dog you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your cat pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Dog acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Dog acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // zhangyong // 如果不是0代狗繁殖,则多收0代狗的繁殖收益 uint256 totalFee = autoBirthFee; Dog storage matron = dogs[_matronId]; if (matron.generation > 0) { totalFee += gen0Profit; } // Checks for payment. require(msg.value >= totalFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don&#39;t need to check that explicitly. // For matron: The caller of this function can&#39;t be the owner of the matron // because the owner of a Dog on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don&#39;t need to spend gas explicitly checking to see if either cat // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron&#39;s owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron // Dog storage matron = dogs[_matronId]; // Make sure matron isn&#39;t pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Dog storage sire = dogs[_sireId]; // Make sure sire isn&#39;t pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these cats are a valid mating pair. require(_isValidMatingPair(matron, _matronId, sire, _sireId)); // All checks passed, Dog gets pregnant! _breedWith(_matronId, _sireId); // zhangyong // 多余的费用返还给用户 uint256 breedExcess = msg.value - totalFee; if (breedExcess > 0) { msg.sender.transfer(breedExcess); } } /// @notice Have a pregnant Dog give birth! /// @param _matronId A Dog ready to give birth. /// @return The Dog ID of the new kitten. /// @dev Looks at a given Dog and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new kitten. The new Dog is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new kitten will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new kitten always goes to the mother&#39;s owner. //zhangyong //只能由系统接生,接生费转给公司作为开发费用,同时避免其他人帮助接生后,后台不知如何处理 function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Dog storage matron = dogs[_matronId]; // Check that the matron is a valid cat. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Dog storage sire = dogs[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } //zhangyong //如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同 uint256 gen0 = matron.generation == 0 ? _matronId : matron.gen0; // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // Make the new kitten! address owner = dogIndexToOwner[_matronId]; uint8 _variation = variation.createVariation(childGenes, dogs.length); bool isGen0Siring = matron.generation == 0; uint256 kittenId = _createDog(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner, _variation, gen0, isGen0Siring); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a Dog gives birth counter is decremented. pregnantDogs--; // Send the balance fee to the person who made birth happen. if(_variation != 0){ variation.registerVariation(kittenId, owner); _transfer(owner, address(variation), kittenId); } // return the new kitten&#39;s ID return kittenId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount, address _to) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can&#39;t just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); uint256 auctioneerCut = computeCut(price); //zhangyong //两只创世狗每次交易需要收取10%的手续费 //创世狗无法繁殖,所以只有创世狗交易才会进入到这个方法 uint256 fee = 0; if (_tokenId == 0 || _tokenId == 1) { fee = price / 5; } require((_bidAmount + auctioneerCut + fee) >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can&#39;t have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer&#39;s cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can&#39;t go negative.) uint256 sellerProceeds = price - auctioneerCut - fee; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it&#39;s an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. // zhangyong // _bidAmount在进入这个方法之前已经扣掉了fee,所以买者需要加上这笔费用才等于开始出价 // uint256 bidExcess = _bidAmount + fee - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. // zhangyong // msg.sender是主合约地址,并不是出价人的地址 // msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, _to); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn&#39;t ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don&#39;t use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We&#39;ve reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can&#39;t overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner&#39;s cut of a sale. /// @param _price - Sale price of NFT. function computeCut(uint256 _price) public view returns (uint256) { // NOTE: We don&#39;t use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 // bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner&#39;s cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work nftAddress.transfer(address(this).balance); } // @dev Creates and begins a new auction. // @param _tokenId - ID of token to auction, sender must be owner. // @param _startingPrice - Price of item (in wei) at beginning of auction. // @param _endingPrice - Price of item (in wei) at end of auction. // @param _duration - Length of time to move between starting // price and ending price (in seconds). // @param _seller - Seller, if not the message sender // function createAuction( // uint256 _tokenId, // uint256 _startingPrice, // uint256 _endingPrice, // uint256 _duration, // address _seller // ) // external // whenNotPaused // { // // Sanity check that no inputs overflow how many bits we&#39;ve allocated // // to store them in the auction struct. // require(_startingPrice == uint256(uint128(_startingPrice))); // require(_endingPrice == uint256(uint128(_endingPrice))); // require(_duration == uint256(uint64(_duration))); // require(_owns(msg.sender, _tokenId)); // _escrow(msg.sender, _tokenId); // Auction memory auction = Auction( // _seller, // uint128(_startingPrice), // uint128(_endingPrice), // uint64(_duration), // uint64(now) // ); // _addAuction(_tokenId, auction); // } // @dev Bids on an open auction, completing the auction and transferring // ownership of the NFT if enough Ether is supplied. // @param _tokenId - ID of token to bid on. // function bid(uint256 _tokenId) // external // payable // whenNotPaused // { // // _bid will throw if the bid or funds transfer fails // _bid(_tokenId, msg.value); // _transfer(msg.sender, _tokenId); // } /// @dev Cancels an auction that hasn&#39;t been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { // zhangyong // 普通用户无法下架创世狗 require(_tokenId > 1); Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be KittyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we&#39;ve allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the KittyCore contract because all bid methods /// should be wrapped. Also returns the Dog to the /// seller rather than the winner. function bid(uint256 _tokenId, address _to) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value, _to); // We transfer the Dog back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of dogs /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 Dog sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we&#39;ve allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId, address _to) external payable { //zhangyong //只能由主合约调用出价竞购,因为要判断当期中奖了的狗无法买卖 require(msg.sender == address(nonFungibleContract)); // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; // zhangyong // 自己不能买自己卖的同一只狗 require(seller != _to); uint256 price = _bid(_tokenId, msg.value, _to); //zhangyong //当狗被拍卖后,主人变成拍卖合约,主合约并不是狗的购买人,需要额外传入 _transfer(_to, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Handles creating auctions for sale and siring of dogs. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract DogAuction is DogBreeding { uint256 public constant GEN0_AUCTION_DURATION = 1 days; // @notice The auction contract variables are defined in KittyBase to allow // us to refer to them in KittyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of dogs. // `siringAuction` refers to the auction for siring rights of dogs. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a Dog up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _dogId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If Dog is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _dogId) || _approvedFor(msg.sender, _dogId)); // Ensure the Dog is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Dog IS allowed to be in a cooldown. require(!isPregnant(_dogId)); _approve(_dogId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Dog. saleAuction.createAuction( _dogId, _startingPrice, _endingPrice, _duration, dogIndexToOwner[_dogId] ); } /// @dev Put a Dog up for auction to be sire. /// Performs checks to ensure the Dog can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _dogId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { //zhangyong Dog storage dog = dogs[_dogId]; //变异狗不能繁殖 require(dog.variation == 0); // Auction contract checks input sizes // If Dog is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _dogId)); require(isReadyToBreed(_dogId)); _approve(_dogId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Dog. siringAuction.createAuction( _dogId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); // zhangyong // 如果不是0代狗繁殖,则多收0代狗的繁殖收益 uint256 totalFee = currentPrice + autoBirthFee; Dog storage matron = dogs[_matronId]; if (matron.generation > 0) { totalFee += gen0Profit; } require(msg.value >= totalFee); uint256 auctioneerCut = saleAuction.computeCut(currentPrice); // Siring auction will throw if the bid fails. siringAuction.bid.value(currentPrice - auctioneerCut)(_sireId, msg.sender); _breedWith(uint32(_matronId), uint32(_sireId)); // zhangyong // 额外的钱返还给用户 uint256 bidExcess = msg.value - totalFee; if (bidExcess > 0) { msg.sender.transfer(bidExcess); } } // zhangyong // 创世狗交易需要收取10%的手续费给CFO // 所有交易都要收取3.75%的手续费给买卖合约 function bidOnSaleAuction( uint256 _dogId ) external payable whenNotPaused { Dog storage dog = dogs[_dogId]; //中奖的狗无法交易 if (dog.generation > 0) { var(,,openBlock,,,,,,) = lottery.getCLottery(); if (dog.birthTime < openBlock) { require(lottery.checkLottery(dog.genes) == 100); } } //交易成功之后,买卖合约会被删除,无法获取到当前价格 uint256 currentPrice = saleAuction.getCurrentPrice(_dogId); require(msg.value >= currentPrice); //创世狗交易需要收取10%的手续费 bool isCreationKitty = _dogId == 0 || _dogId == 1; uint256 fee = 0; if (isCreationKitty) { fee = currentPrice / 5; } uint256 auctioneerCut = saleAuction.computeCut(currentPrice); saleAuction.bid.value(currentPrice - (auctioneerCut + fee))(_dogId, msg.sender); // 创世狗被交易之后,下次的价格为当前成交价的2倍 if (isCreationKitty) { //转账到主合约进行,因为买卖合约访问不了cfoAddress cfoAddress.transfer(fee); uint256 nextPrice = uint256(uint128(2 * currentPrice)); if (nextPrice < currentPrice) { nextPrice = currentPrice; } _approve(_dogId, saleAuction); saleAuction.createAuction( _dogId, nextPrice, nextPrice, GEN0_AUCTION_DURATION, msg.sender); } uint256 bidExcess = msg.value - currentPrice; if (bidExcess > 0) { msg.sender.transfer(bidExcess); } } // @dev Transfers the balance of the sale auction contract // to the KittyCore contract. We use two-step withdrawal to // prevent two transfer calls in the auction bid function. // function withdrawAuctionBalances() external onlyCLevel { // saleAuction.withdrawBalance(); // siringAuction.withdrawBalance(); // } } /// @title all functions related to creating kittens contract DogMinting is DogAuction { // Limits the number of cats the contract owner can ever create. // uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 40000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 200 finney; // uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created. // uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // @dev we can create promo kittens, up to a limit. Only callable by COO // @param _genes the encoded genes of the kitten to be created, any value is accepted // @param _owner the future owner of the created kittens. Default to contract COO // function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { // address kittyOwner = _owner; // if (kittyOwner == address(0)) { // kittyOwner = cooAddress; // } // require(promoCreatedCount < PROMO_CREATION_LIMIT); // promoCreatedCount++; // //zhangyong // //增加变异系数与0代狗祖先作为参数 // _createDog(0, 0, 0, _genes, kittyOwner, 0, 0, false); // } // @dev Creates a new gen0 Dog with the given genes function createGen0Dog(uint256 _genes) external onlyCLevel returns(uint256) { require(gen0CreatedCount < GEN0_CREATION_LIMIT); //zhangyong //增加变异系数与0代狗祖先作为参数 uint256 dogId = _createDog(0, 0, 0, _genes, address(this), 0, 0, false); _approve(dogId, msg.sender); gen0CreatedCount++; return dogId; } /// @dev creates an auction for it. // function createGen0Auction(uint256 _dogId) external onlyCOO { // require(_owns(address(this), _dogId)); // _approve(_dogId, saleAuction); // //zhangyong // //0代狗的价格随时间递减到最低价,起始价与前5只价格相关 // uint256 price = _computeNextGen0Price(); // saleAuction.createAuction( // _dogId, // price, // price, // GEN0_AUCTION_DURATION, // address(this) // ); // } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function computeNextGen0Price() public view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don&#39;t overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title Cryptodogs: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main Cryptodogs contract, keeps track of kittens so they don&#39;t wander around and get lost. contract DogCore is DogMinting { // This is the main Cryptodogs contract. In order to keep our code seperated into logical sections, // we&#39;ve broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there&#39;s always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // Dog ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don&#39;t worry, I&#39;m sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - KittyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - KittyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - KittyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - KittyBreeding: This file contains the methods necessary to breed cats together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. // We can make up to 5000 "promo" cats that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 cats. After that, it&#39;s all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main Cryptodogs smart contract instance. function DogCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical kitten 0 - so we don&#39;t have generation-0 parent issues //zhangyong //增加变异系数与0代狗祖先作为参数 _createDog(0, 0, 0, uint256(0), address(this), 0, 0, false); _approve(0, cooAddress); _createDog(0, 0, 0, uint256(0), address(this), 0, 0, false); _approve(1, cooAddress); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It&#39;s up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it&#39;s from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) || msg.sender == ceoAddress ); } /// @notice Returns all the relevant information about a specific Dog. /// @param _id The ID of the Dog of interest. function getDog(uint256 _id) external view returns ( uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes, uint8 variation, uint256 gen0 ) { Dog storage dog = dogs[_id]; // if this variable is 0 then it&#39;s not gestating cooldownIndex = uint256(dog.cooldownIndex); nextActionAt = uint256(dog.cooldownEndBlock); siringWithId = uint256(dog.siringWithId); birthTime = uint256(dog.birthTime); matronId = uint256(dog.matronId); sireId = uint256(dog.sireId); generation = uint256(dog.generation); genes = uint256(dog.genes); variation = uint8(dog.variation); gen0 = uint256(dog.gen0); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can&#39;t have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(lottery != address(0)); require(variation != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function setLotteryAddress(address _address) external onlyCEO { LotteryInterface candidateContract = LotteryInterface(_address); require(candidateContract.isLottery()); lottery = candidateContract; } function setVariationAddress(address _address) external onlyCEO { VariationInterface candidateContract = VariationInterface(_address); require(candidateContract.isVariation()); variation = candidateContract; } function registerLottery(uint256 _dogId) external returns (uint8) { require(_owns(msg.sender, _dogId)); require(lottery.registerLottery(_dogId) == 0); _transfer(msg.sender, address(lottery), _dogId); } function sendMoney(address _to, uint256 _money) external { require(msg.sender == address(lottery) || msg.sender == address(variation)); require(address(this).balance >= _money); _to.transfer(_money); } }
@dev Computes the next gen0 auction starting price, given the average of the past 5 prices + 50%. Sanity check to ensure we don&#39;t overflow arithmetic We never auction for less than starting price
function computeNextGen0Price() public view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; }
2,460,445
[ 1, 10743, 326, 1024, 3157, 20, 279, 4062, 5023, 6205, 16, 864, 225, 326, 8164, 434, 326, 8854, 1381, 19827, 397, 6437, 9, 18, 23123, 866, 358, 3387, 732, 2727, 10, 5520, 31, 88, 9391, 30828, 1660, 5903, 279, 4062, 364, 5242, 2353, 5023, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3671, 2134, 7642, 20, 5147, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 279, 537, 5147, 273, 272, 5349, 37, 4062, 18, 15621, 7642, 20, 30746, 5147, 5621, 203, 203, 3639, 2583, 12, 836, 5147, 422, 2254, 5034, 12, 11890, 10392, 12, 836, 5147, 3719, 1769, 203, 203, 3639, 2254, 5034, 1024, 5147, 273, 279, 537, 5147, 397, 261, 836, 5147, 342, 576, 1769, 203, 203, 3639, 309, 261, 4285, 5147, 411, 611, 1157, 20, 67, 7570, 1360, 67, 7698, 1441, 13, 288, 203, 5411, 1024, 5147, 273, 611, 1157, 20, 67, 7570, 1360, 67, 7698, 1441, 31, 203, 3639, 289, 203, 203, 3639, 327, 1024, 5147, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x9f49f8FA369449c6E7918D2EeaEF13b89b5af9F8/sources/project:/contracts/Barnaje.sol
USDT token contract interface
IERC20 private usdt;
3,262,709
[ 1, 3378, 9081, 1147, 6835, 1560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 467, 654, 39, 3462, 3238, 584, 7510, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x78a486306D15E7111cca541F2f1307a1cFCaF5C4/sources/contracts/Peronio.sol
* Return the number of PE tokens in existence @return peAmount Number of PE tokens in existence/
function _totalSupply() internal view returns (PeQuantity peAmount) { peAmount = PeQuantity.wrap(totalSupply()); }
4,798,443
[ 1, 990, 326, 1300, 434, 16628, 2430, 316, 15782, 327, 2804, 6275, 225, 3588, 434, 16628, 2430, 316, 15782, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4963, 3088, 1283, 1435, 2713, 1476, 1135, 261, 11227, 12035, 2804, 6275, 13, 288, 203, 3639, 2804, 6275, 273, 19622, 12035, 18, 4113, 12, 4963, 3088, 1283, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* https://t.me/MasterPlan_ETH */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } contract MASTERPLAN is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Master Plan";// string private constant _symbol = "MASTERPLAN";// uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; //Buy Fee uint256 private _redisFeeOnBuy = 0;// uint256 private _taxFeeOnBuy = 10;// //Sell Fee uint256 private _redisFeeOnSell = 0;// uint256 private _taxFeeOnSell = 10;// //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0x63d2E9E923E5Ea16F0929ced98Dd8340b1aB3736); // insert dev address here address payable private _marketingAddress = payable(0x32E60009323B3c12aA299DA54B85f0a80dB8cAe1); // insert marketing address here IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 15000000 * 10**9; // uint256 public _maxSellTxAmount = 5000000 * 10**9; // uint256 public _maxBuyTxAmount = 15000000 * 10**9; // uint256 public _maxWalletSize = 30000000 * 10**9; // uint256 public _swapTokensAtAmount = 10000 * 10**9; // event MaxTxAmountUpdated(uint256 _maxTxAmount); event MaxBuyTxAmountUpdated(uint256 _maxBuyTxAmount); event MaxSellTxAmountUpdated(uint256 _maxSellTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);// uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { //Trade start check if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } //block 0 ban since we're launching unverified if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee and max limit for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } //Set Fee and limit for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _marketingAddress.transfer(amount); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchBlock = block.number; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { require(redisFeeOnBuy >= 0 && redisFeeOnBuy <= 2, "Buy rewards must be between 0% and 2%"); require(taxFeeOnBuy >= 0 && taxFeeOnBuy <= 15, "Buy tax must be between 0% and 15%"); require(redisFeeOnSell >= 0 && redisFeeOnSell <= 2, "Sell rewards must be between 0% and 2%"); require(taxFeeOnSell >= 0 && taxFeeOnSell <= 15, "Sell tax must be between 0% and 15%"); _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set maximum transaction function setMaxTxnAmounts(uint256 maxBuyTxAmount, uint256 maxSellTxAmount) public onlyOwner { require(maxBuyTxAmount >= 5000000, "Buy Tx Limit must be high enough to not honeypot"); require(maxSellTxAmount >= 5000000, "Sell Tx Limit must be high enough to not honeypot"); _maxBuyTxAmount = maxBuyTxAmount * 10**9; _maxSellTxAmount = maxSellTxAmount * 10**9; _maxTxAmount = maxBuyTxAmount * 10**9; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize * 10**9; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
Buy FeeSell FeeOriginal Fee
contract MASTERPLAN is Context, IERC20, Ownable { using SafeMath for uint256; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; event MaxTxAmountUpdated(uint256 _maxTxAmount); event MaxBuyTxAmountUpdated(uint256 _maxBuyTxAmount); event MaxSellTxAmountUpdated(uint256 _maxSellTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; require(amount <= _maxBuyTxAmount, "TOKEN: Max Buy Transaction Limit"); } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; require(amount <= _maxSellTxAmount, "TOKEN: Max Sell Transaction Limit"); } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _marketingAddress.transfer(amount); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchBlock = block.number; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { require(redisFeeOnBuy >= 0 && redisFeeOnBuy <= 2, "Buy rewards must be between 0% and 2%"); require(taxFeeOnBuy >= 0 && taxFeeOnBuy <= 15, "Buy tax must be between 0% and 15%"); require(redisFeeOnSell >= 0 && redisFeeOnSell <= 2, "Sell rewards must be between 0% and 2%"); require(taxFeeOnSell >= 0 && taxFeeOnSell <= 15, "Sell tax must be between 0% and 15%"); _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmounts(uint256 maxBuyTxAmount, uint256 maxSellTxAmount) public onlyOwner { require(maxBuyTxAmount >= 5000000, "Buy Tx Limit must be high enough to not honeypot"); require(maxSellTxAmount >= 5000000, "Sell Tx Limit must be high enough to not honeypot"); _maxBuyTxAmount = maxBuyTxAmount * 10**9; _maxSellTxAmount = maxSellTxAmount * 10**9; _maxTxAmount = maxBuyTxAmount * 10**9; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize * 10**9; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
11,648,493
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 27312, 6253, 1258, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 7010, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 7010, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 3784, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 565, 2254, 5034, 1071, 8037, 1768, 31, 203, 7010, 7010, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 273, 389, 12311, 14667, 1398, 55, 1165, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 273, 389, 8066, 14667, 1398, 55, 1165, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 11515, 12311, 14667, 273, 389, 12311, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 1484, 522, 83, 641, 651, 14667, 273, 389, 8066, 14667, 31, 203, 7010, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 2512, 87, 31, 203, 565, 2874, 12, 2867, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-11-02 */ // Sources flattened with hardhat v2.6.5 https://hardhat.org // File @animoca/ethereum-contracts-core-1.1.2/contracts/utils/types/[email protected] // SPDX-License-Identifier: MIT // Partially derived from OpenZeppelin: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/406c83649bd6169fc1b578e08506d78f0873b276/contracts/utils/Address.sol pragma solidity >=0.7.6 <0.8.0; /** * @dev Upgrades the address type to check if it is a contract. */ library AddressIsContract { /** * @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; assembly { size := extcodesize(account) } return size > 0; } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/utils/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @title ERC20Wrapper * Wraps ERC20 functions to support non-standard implementations which do not return a bool value. * Calls to the wrapped functions revert only if they throw or if they return false. */ library ERC20Wrapper { using AddressIsContract for address; function wrappedTransfer( IWrappedERC20 token, address to, uint256 value ) internal { _callWithOptionalReturnData(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function wrappedTransferFrom( IWrappedERC20 token, address from, address to, uint256 value ) internal { _callWithOptionalReturnData(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function wrappedApprove( IWrappedERC20 token, address spender, uint256 value ) internal { _callWithOptionalReturnData(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function _callWithOptionalReturnData(IWrappedERC20 token, bytes memory callData) internal { address target = address(token); require(target.isContract(), "ERC20Wrapper: non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = target.call(callData); if (success) { if (data.length != 0) { require(abi.decode(data, (bool)), "ERC20Wrapper: operation failed"); } } else { // revert using a standard revert message if (data.length == 0) { revert("ERC20Wrapper: operation failed"); } // revert using the revert message coming from the call assembly { let size := mload(data) revert(add(32, data), size) } } } } interface IWrappedERC20 { function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function approve(address spender, uint256 value) external returns (bool); } // File @animoca/ethereum-contracts-core-1.1.2/contracts/algo/[email protected] // Derived from OpenZeppelin: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/406c83649bd6169fc1b578e08506d78f0873b276/contracts/utils/structs/EnumerableMap.sol pragma solidity >=0.7.6 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumMap for EnumMap.Map; * * // Declare a set state variable * EnumMap.Map private myMap; * } * ``` */ library EnumMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // This means that we can only create new EnumMaps for types that fit // in bytes32. struct MapEntry { bytes32 key; bytes32 value; } struct Map { // Storage of map keys and values MapEntry[] entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( Map storage map, bytes32 key, bytes32 value ) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map.indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map.entries.push(MapEntry({key: key, value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map.indexes[key] = map.entries.length; return true; } else { map.entries[keyIndex - 1].value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(Map storage map, bytes32 key) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map.indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map.entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map.entries[lastIndex]; // Move the last entry to the index where the entry to delete is map.entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map.indexes[lastEntry.key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map.entries.pop(); // Delete the index for the deleted slot delete map.indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function contains(Map storage map, bytes32 key) internal view returns (bool) { return map.indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function length(Map storage map) internal view returns (uint256) { return map.entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Map storage map, uint256 index) internal view returns (bytes32, bytes32) { require(map.entries.length > index, "EnumMap: index out of bounds"); MapEntry storage entry = map.entries[index]; return (entry.key, entry.value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(Map storage map, bytes32 key) internal view returns (bytes32) { uint256 keyIndex = map.indexes[key]; require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key) return map.entries[keyIndex - 1].value; // All indexes are 1-based } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/algo/[email protected] // Derived from OpenZeppelin: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/406c83649bd6169fc1b578e08506d78f0873b276/contracts/utils/structs/EnumerableSet.sol pragma solidity >=0.7.6 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumSet for EnumSet.Set; * * // Declare a set state variable * EnumSet.Set private mySet; * } * ``` */ library EnumSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)) { set.values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set.indexes[value] = set.values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Set storage set, bytes32 value) internal returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set.indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set.values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set.values[lastIndex]; // Move the last value to the index where the value to delete is set.values[toDeleteIndex] = lastvalue; // Update the index for the moved value set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set.values.pop(); // Delete the index for the deleted slot delete set.indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Set storage set, bytes32 value) internal view returns (bool) { return set.indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(Set storage set) internal view returns (uint256) { return set.values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Set storage set, uint256 index) internal view returns (bytes32) { require(set.values.length > index, "EnumSet: index out of bounds"); return set.values[index]; } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/metatx/[email protected] pragma solidity >=0.7.6 <0.8.0; /* * Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner. */ abstract contract ManagedIdentity { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/access/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @title ERC-173 Contract Ownership Standard * Note: the ERC-165 identifier for this interface is 0x7f5828d0 */ interface IERC173 { /** * Event emited when ownership of a contract changes. * @param previousOwner the previous owner. * @param newOwner the new owner. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * Get the address of the owner * @return The address of the owner. */ function owner() external view returns (address); /** * Set the address of the new owner of the contract * Set newOwner to address(0) to renounce any ownership. * @dev Emits an {OwnershipTransferred} event. * @param newOwner The address of the new owner of the contract. Using the zero address means renouncing ownership. */ function transferOwnership(address newOwner) external; } // File @animoca/ethereum-contracts-core-1.1.2/contracts/access/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is ManagedIdentity, IERC173 { address internal _owner; /** * Initializes the contract, setting the deployer as the initial owner. * @dev Emits an {IERC173-OwnershipTransferred(address,address)} event. */ constructor(address owner_) { _owner = owner_; emit OwnershipTransferred(address(0), owner_); } /** * Gets the address of the current contract owner. */ function owner() public view virtual override returns (address) { return _owner; } /** * See {IERC173-transferOwnership(address)} * @dev Reverts if the sender is not the current contract owner. * @param newOwner the address of the new owner. Use the zero address to renounce the ownership. */ function transferOwnership(address newOwner) public virtual override { _requireOwnership(_msgSender()); _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } /** * @dev Reverts if `account` is not the contract owner. * @param account the account to test. */ function _requireOwnership(address account) internal virtual { require(account == this.owner(), "Ownable: not the owner"); } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/payment/[email protected] pragma solidity >=0.7.6 <0.8.0; /** @title PayoutWallet @dev adds support for a payout wallet Note: . */ abstract contract PayoutWallet is ManagedIdentity, Ownable { event PayoutWalletSet(address payoutWallet_); address payable public payoutWallet; constructor(address owner, address payable payoutWallet_) Ownable(owner) { require(payoutWallet_ != address(0), "Payout: zero address"); payoutWallet = payoutWallet_; emit PayoutWalletSet(payoutWallet_); } function setPayoutWallet(address payable payoutWallet_) public { _requireOwnership(_msgSender()); require(payoutWallet_ != address(0), "Payout: zero address"); payoutWallet = payoutWallet_; emit PayoutWalletSet(payoutWallet); } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/lifecycle/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * Contract module which allows derived contracts to implement a mechanism for * activating, or 'starting', a contract. * * This module is used through inheritance. It will make available the modifiers * `whenNotStarted` and `whenStarted`, which can be applied to the functions of * your contract. Those functions will only be 'startable' once the modifiers * are put in place. */ abstract contract Startable is ManagedIdentity { event Started(address account); uint256 private _startedAt; /** * Modifier to make a function callable only when the contract has not started. */ modifier whenNotStarted() { require(_startedAt == 0, "Startable: started"); _; } /** * Modifier to make a function callable only when the contract has started. */ modifier whenStarted() { require(_startedAt != 0, "Startable: not started"); _; } /** * Constructor. */ constructor() {} /** * Returns the timestamp when the contract entered the started state. * @return The timestamp when the contract entered the started state. */ function startedAt() public view returns (uint256) { return _startedAt; } /** * Triggers the started state. * @dev Emits the Started event when the function is successfully called. */ function _start() internal virtual whenNotStarted { _startedAt = block.timestamp; emit Started(_msgSender()); } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/lifecycle/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @dev Contract which allows children to implement pausability. */ abstract contract Pausable is ManagedIdentity { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool public paused; constructor(bool paused_) { paused = paused_; } function _requireNotPaused() internal view { require(!paused, "Pausable: paused"); } function _requirePaused() internal view { require(paused, "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual { _requireNotPaused(); paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual { _requirePaused(); paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // File @animoca/ethereum-contracts-sale-2.0.0/contracts/sale/interfaces/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @title ISale * * An interface for a contract which allows merchants to display products and customers to purchase them. * * Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an * explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment * tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means * this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment. * * The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used * to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver * contract address can be set for a SKU at its creation: if the value is different from the zero address, * the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU. * * This interface is designed to be consistent while managing a variety of implementation scenarios. It is * also intended to be developer-friendly: all vital information is consistently deductible from the events * (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented). */ interface ISale { /** * Event emitted to notify about the magic values necessary for interfacing with this contract. * @param names An array of names for the magic values used by the contract. * @param values An array of values for the magic values used by the contract. */ event MagicValues(bytes32[] names, bytes32[] values); /** * Event emitted to notify about the creation of a SKU. * @param sku The identifier of the created SKU. * @param totalSupply The initial total supply for sale. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after * each purchase. If this is the zero address, the call is not enabled. */ event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver); /** * Event emitted to notify about a change in the pricing of a SKU. * @dev `tokens` and `prices` arrays MUST have the same length. * @param sku The identifier of the updated SKU. * @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled. * @param prices An array of updated prices for each of the payment tokens. * Zero price values are used for payment tokens being disabled. */ event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices); /** * Event emitted to notify about a purchase. * @param purchaser The initiater and buyer of the purchase. * @param recipient The recipient of the purchase. * @param token The token used as the currency for the payment. * @param sku The identifier of the purchased SKU. * @param quantity The purchased quantity. * @param userData Optional extra user input data. * @param totalPrice The amount of `token` paid. * @param extData Implementation-specific extra purchase data, such as * details about discounts applied, conversion rates, purchase receipts, etc. */ event Purchase( address indexed purchaser, address recipient, address indexed token, bytes32 indexed sku, uint256 quantity, bytes userData, uint256 totalPrice, bytes extData ); /** * Returns the magic value used to represent the ETH payment token. * @dev MUST NOT be the zero address. * @return the magic value used to represent the ETH payment token. */ // solhint-disable-next-line func-name-mixedcase function TOKEN_ETH() external pure returns (address); /** * Returns the magic value used to represent an infinite, never-decreasing SKU's supply. * @dev MUST NOT be zero. * @return the magic value used to represent an infinite, never-decreasing SKU's supply. */ // solhint-disable-next-line func-name-mixedcase function SUPPLY_UNLIMITED() external pure returns (uint256); /** * Performs a purchase. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the address zero. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @dev Emits the Purchase event. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. */ function purchaseFor( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external payable; /** * Estimates the computed final total amount to pay for a purchase, including any potential discount. * @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time). * @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @param recipient The recipient of the purchase used to calculate the total price amount. * @param token The payment token used to calculate the total price amount. * @param sku The identifier of the SKU used to calculate the total price amount. * @param quantity The quantity used to calculate the total price amount. * @param userData Optional extra user input data. * @return totalPrice The computed total price to pay. * @return pricingData Implementation-specific extra pricing data, such as details about discounts applied. * If not empty, the implementer MUST document how to interepret the values. */ function estimatePurchase( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external view returns (uint256 totalPrice, bytes32[] memory pricingData); /** * Returns the information relative to a SKU. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of payment tokens is bounded, so that this function does not run out of gas. * @dev Reverts if `sku` does not exist. * @param sku The SKU identifier. * @return totalSupply The initial total supply for sale. * @return remainingSupply The remaining supply for sale. * @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function. * @return tokens The list of supported payment tokens. * @return prices The list of associated prices for each of the `tokens`. */ function getSkuInfo(bytes32 sku) external view returns ( uint256 totalSupply, uint256 remainingSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver, address[] memory tokens, uint256[] memory prices ); /** * Returns the list of created SKU identifiers. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of SKUs is bounded, so that this function does not run out of gas. * @return skus the list of created SKU identifiers. */ function getSkus() external view returns (bytes32[] memory skus); } // File @animoca/ethereum-contracts-sale-2.0.0/contracts/sale/interfaces/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @title IPurchaseNotificationsReceiver * Interface for any contract that wants to support purchase notifications from a Sale contract. */ interface IPurchaseNotificationsReceiver { /** * Handles the receipt of a purchase notification. * @dev This function MUST return the function selector, otherwise the caller will revert the transaction. * The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector` * @dev This function MAY throw. * @param purchaser The purchaser of the purchase. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. * @param totalPrice The total price paid. * @param pricingData Implementation-specific extra pricing data, such as details about discounts applied. * @param paymentData Implementation-specific extra payment data, such as conversion rates. * @param deliveryData Implementation-specific extra delivery data, such as purchase receipts. * @return `bytes4(keccak256( * "onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))` */ function onPurchaseNotificationReceived( address purchaser, address recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData, uint256 totalPrice, bytes32[] calldata pricingData, bytes32[] calldata paymentData, bytes32[] calldata deliveryData ) external returns (bytes4); } // File @animoca/ethereum-contracts-sale-2.0.0/contracts/sale/abstract/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @title PurchaseLifeCycles * An abstract contract which define the life cycles for a purchase implementer. */ abstract contract PurchaseLifeCycles { /** * Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions. */ struct PurchaseData { address payable purchaser; address payable recipient; address token; bytes32 sku; uint256 quantity; bytes userData; uint256 totalPrice; bytes32[] pricingData; bytes32[] paymentData; bytes32[] deliveryData; } /* Internal Life Cycle Functions */ /** * `estimatePurchase` lifecycle. * @param purchase The purchase conditions. */ function _estimatePurchase(PurchaseData memory purchase) internal view virtual returns (uint256 totalPrice, bytes32[] memory pricingData) { _validation(purchase); _pricing(purchase); totalPrice = purchase.totalPrice; pricingData = purchase.pricingData; } /** * `purchaseFor` lifecycle. * @param purchase The purchase conditions. */ function _purchaseFor(PurchaseData memory purchase) internal virtual { _validation(purchase); _pricing(purchase); _payment(purchase); _delivery(purchase); _notification(purchase); } /* Internal Life Cycle Step Functions */ /** * Lifecycle step which validates the purchase pre-conditions. * @dev Responsibilities: * - Ensure that the purchase pre-conditions are met and revert if not. * @param purchase The purchase conditions. */ function _validation(PurchaseData memory purchase) internal view virtual; /** * Lifecycle step which computes the purchase price. * @dev Responsibilities: * - Computes the pricing formula, including any discount logic and price conversion; * - Set the value of `purchase.totalPrice`; * - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it. * @param purchase The purchase conditions. */ function _pricing(PurchaseData memory purchase) internal view virtual; /** * Lifecycle step which manages the transfer of funds from the purchaser. * @dev Responsibilities: * - Ensure the payment reaches destination in the expected output token; * - Handle any token swap logic; * - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it. * @param purchase The purchase conditions. */ function _payment(PurchaseData memory purchase) internal virtual; /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update; * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual; /** * Lifecycle step which notifies of the purchase. * @dev Responsibilities: * - Manage after-purchase event(s) emission. * - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable. * @param purchase The purchase conditions. */ function _notification(PurchaseData memory purchase) internal virtual; } // File @animoca/ethereum-contracts-sale-2.0.0/contracts/sale/abstract/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @title Sale * An abstract base sale contract with a minimal implementation of ISale and administration functions. * A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions * are provided, but the inheriting contract must implement `_pricing` and `_payment`. */ abstract contract Sale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable { using AddressIsContract for address; using SafeMath for uint256; using EnumSet for EnumSet.Set; using EnumMap for EnumMap.Map; struct SkuInfo { uint256 totalSupply; uint256 remainingSupply; uint256 maxQuantityPerPurchase; address notificationsReceiver; EnumMap.Map prices; } address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max; EnumSet.Set internal _skus; mapping(bytes32 => SkuInfo) internal _skuInfos; uint256 internal immutable _skusCapacity; uint256 internal immutable _tokensPerSkuCapacity; /** * Constructor. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param payoutWallet_ the payout wallet. * @param skusCapacity the cap for the number of managed SKUs. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address payable payoutWallet_, uint256 skusCapacity, uint256 tokensPerSkuCapacity ) PayoutWallet(msg.sender, payoutWallet_) Pausable(true) { _skusCapacity = skusCapacity; _tokensPerSkuCapacity = tokensPerSkuCapacity; bytes32[] memory names = new bytes32[](2); bytes32[] memory values = new bytes32[](2); (names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH))); (names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED))); emit MagicValues(names, values); } /* Public Admin Functions */ /** * Actvates, or 'starts', the contract. * @dev Emits the `Started` event. * @dev Emits the `Unpaused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has already been started. * @dev Reverts if the contract is not paused. */ function start() public virtual { _requireOwnership(_msgSender()); _start(); _unpause(); } /** * Pauses the contract. * @dev Emits the `Paused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has not been started yet. * @dev Reverts if the contract is already paused. */ function pause() public virtual whenStarted { _requireOwnership(_msgSender()); _pause(); } /** * Resumes the contract. * @dev Emits the `Unpaused` event. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if the contract has not been started yet. * @dev Reverts if the contract is not paused. */ function unpause() public virtual whenStarted { _requireOwnership(_msgSender()); _unpause(); } /** * Sets the token prices for the specified product SKU. * @dev Reverts if called by any other than the contract owner. * @dev Reverts if `tokens` and `prices` have different lengths. * @dev Reverts if `sku` does not exist. * @dev Reverts if one of the `tokens` is the zero address. * @dev Reverts if the update results in too many tokens for the SKU. * @dev Emits the `SkuPricingUpdate` event. * @param sku The identifier of the SKU. * @param tokens The list of payment tokens to update. * If empty, disable all the existing payment tokens. * @param prices The list of prices to apply for each payment token. * Zero price values are used to disable a payment token. */ function updateSkuPricing( bytes32 sku, address[] memory tokens, uint256[] memory prices ) public virtual { _requireOwnership(_msgSender()); uint256 length = tokens.length; require(length == prices.length, "Sale: inconsistent arrays"); SkuInfo storage skuInfo = _skuInfos[sku]; require(skuInfo.totalSupply != 0, "Sale: non-existent sku"); EnumMap.Map storage tokenPrices = skuInfo.prices; if (length == 0) { uint256 currentLength = tokenPrices.length(); for (uint256 i = 0; i < currentLength; ++i) { // TODO add a clear function in EnumMap and EnumSet and use it (bytes32 token, ) = tokenPrices.at(0); tokenPrices.remove(token); } } else { _setTokenPrices(tokenPrices, tokens, prices); } emit SkuPricingUpdate(sku, tokens, prices); } /* ISale Public Functions */ /** * Performs a purchase. * @dev Reverts if the sale has not started. * @dev Reverts if the sale is paused. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @dev Emits the Purchase event. * @param recipient The recipient of the purchase. * @param token The token to use as the payment currency. * @param sku The identifier of the SKU to purchase. * @param quantity The quantity to purchase. * @param userData Optional extra user input data. */ function purchaseFor( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external payable virtual override whenStarted { _requireNotPaused(); PurchaseData memory purchase; purchase.purchaser = _msgSender(); purchase.recipient = recipient; purchase.token = token; purchase.sku = sku; purchase.quantity = quantity; purchase.userData = userData; _purchaseFor(purchase); } /** * Estimates the computed final total amount to pay for a purchase, including any potential discount. * @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time). * @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values. * @dev Reverts if the sale has not started. * @dev Reverts if the sale is paused. * @dev Reverts if `recipient` is the zero address. * @dev Reverts if `token` is the zero address. * @dev Reverts if `quantity` is zero. * @dev Reverts if `quantity` is greater than the maximum purchase quantity. * @dev Reverts if `quantity` is greater than the remaining supply. * @dev Reverts if `sku` does not exist. * @dev Reverts if `sku` exists but does not have a price set for `token`. * @param recipient The recipient of the purchase used to calculate the total price amount. * @param token The payment token used to calculate the total price amount. * @param sku The identifier of the SKU used to calculate the total price amount. * @param quantity The quantity used to calculate the total price amount. * @param userData Optional extra user input data. * @return totalPrice The computed total price. * @return pricingData Implementation-specific extra pricing data, such as details about discounts applied. * If not empty, the implementer MUST document how to interepret the values. */ function estimatePurchase( address payable recipient, address token, bytes32 sku, uint256 quantity, bytes calldata userData ) external view virtual override whenStarted returns (uint256 totalPrice, bytes32[] memory pricingData) { _requireNotPaused(); PurchaseData memory purchase; purchase.purchaser = _msgSender(); purchase.recipient = recipient; purchase.token = token; purchase.sku = sku; purchase.quantity = quantity; purchase.userData = userData; return _estimatePurchase(purchase); } /** * Returns the information relative to a SKU. * @dev WARNING: it is the responsibility of the implementer to ensure that the * number of payment tokens is bounded, so that this function does not run out of gas. * @dev Reverts if `sku` does not exist. * @param sku The SKU identifier. * @return totalSupply The initial total supply for sale. * @return remainingSupply The remaining supply for sale. * @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function. * @return tokens The list of supported payment tokens. * @return prices The list of associated prices for each of the `tokens`. */ function getSkuInfo(bytes32 sku) external view override returns ( uint256 totalSupply, uint256 remainingSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver, address[] memory tokens, uint256[] memory prices ) { SkuInfo storage skuInfo = _skuInfos[sku]; uint256 length = skuInfo.prices.length(); totalSupply = skuInfo.totalSupply; require(totalSupply != 0, "Sale: non-existent sku"); remainingSupply = skuInfo.remainingSupply; maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase; notificationsReceiver = skuInfo.notificationsReceiver; tokens = new address[](length); prices = new uint256[](length); for (uint256 i = 0; i < length; ++i) { (bytes32 token, bytes32 price) = skuInfo.prices.at(i); tokens[i] = address(uint256(token)); prices[i] = uint256(price); } } /** * Returns the list of created SKU identifiers. * @return skus the list of created SKU identifiers. */ function getSkus() external view override returns (bytes32[] memory skus) { skus = _skus.values; } /* Internal Utility Functions */ /** * Creates an SKU. * @dev Reverts if `totalSupply` is zero. * @dev Reverts if `sku` already exists. * @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address. * @dev Reverts if the update results in too many SKUs. * @dev Emits the `SkuCreation` event. * @param sku the SKU identifier. * @param totalSupply the initial total supply. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param notificationsReceiver The purchase notifications receiver contract address. * If set to the zero address, the notification is not enabled. */ function _createSku( bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver ) internal virtual { require(totalSupply != 0, "Sale: zero supply"); require(_skus.length() < _skusCapacity, "Sale: too many skus"); require(_skus.add(sku), "Sale: sku already created"); if (notificationsReceiver != address(0)) { require(notificationsReceiver.isContract(), "Sale: non-contract receiver"); } SkuInfo storage skuInfo = _skuInfos[sku]; skuInfo.totalSupply = totalSupply; skuInfo.remainingSupply = totalSupply; skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase; skuInfo.notificationsReceiver = notificationsReceiver; emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver); } /** * Updates SKU token prices. * @dev Reverts if one of the `tokens` is the zero address. * @dev Reverts if the update results in too many tokens for the SKU. * @param tokenPrices Storage pointer to a mapping of SKU token prices to update. * @param tokens The list of payment tokens to update. * @param prices The list of prices to apply for each payment token. * Zero price values are used to disable a payment token. */ function _setTokenPrices( EnumMap.Map storage tokenPrices, address[] memory tokens, uint256[] memory prices ) internal virtual { for (uint256 i = 0; i < tokens.length; ++i) { address token = tokens[i]; require(token != address(0), "Sale: zero address token"); uint256 price = prices[i]; if (price == 0) { tokenPrices.remove(bytes32(uint256(token))); } else { tokenPrices.set(bytes32(uint256(token)), bytes32(price)); } } require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens"); } /* Internal Life Cycle Step Functions */ /** * Lifecycle step which validates the purchase pre-conditions. * @dev Responsibilities: * - Ensure that the purchase pre-conditions are met and revert if not. * @dev Reverts if `purchase.recipient` is the zero address. * @dev Reverts if `purchase.token` is the zero address. * @dev Reverts if `purchase.quantity` is zero. * @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`. * @dev Reverts if `purchase.quantity` is greater than the available supply. * @dev Reverts if `purchase.sku` does not exist. * @dev Reverts if `purchase.sku` exists but does not have a price set for `purchase.token`. * @dev If this function is overriden, the implementer SHOULD super call this before. * @param purchase The purchase conditions. */ function _validation(PurchaseData memory purchase) internal view virtual override { require(purchase.recipient != address(0), "Sale: zero address recipient"); require(purchase.token != address(0), "Sale: zero address token"); require(purchase.quantity != 0, "Sale: zero quantity purchase"); SkuInfo storage skuInfo = _skuInfos[purchase.sku]; require(skuInfo.totalSupply != 0, "Sale: non-existent sku"); require(skuInfo.maxQuantityPerPurchase >= purchase.quantity, "Sale: above max quantity"); if (skuInfo.totalSupply != SUPPLY_UNLIMITED) { require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply"); } bytes32 priceKey = bytes32(uint256(purchase.token)); require(skuInfo.prices.contains(priceKey), "Sale: non-existent sku token"); } /** * Lifecycle step which delivers the purchased SKUs to the recipient. * @dev Responsibilities: * - Ensure the product is delivered to the recipient, if that is the contract's responsibility. * - Handle any internal logic related to the delivery, including the remaining supply update; * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it. * @dev Reverts if there is not enough available supply. * @dev If this function is overriden, the implementer SHOULD super call it. * @param purchase The purchase conditions. */ function _delivery(PurchaseData memory purchase) internal virtual override { SkuInfo storage skuInfo = _skuInfos[purchase.sku]; if (skuInfo.totalSupply != SUPPLY_UNLIMITED) { _skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity); } } /** * Lifecycle step which notifies of the purchase. * @dev Responsibilities: * - Manage after-purchase event(s) emission. * - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable. * @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value. * @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData` * and `deliveryData`. If not empty, the implementer MUST document how to interpret these values. * @dev If this function is overriden, the implementer SHOULD super call it. * @param purchase The purchase conditions. */ function _notification(PurchaseData memory purchase) internal virtual override { emit Purchase( purchase.purchaser, purchase.recipient, purchase.token, purchase.sku, purchase.quantity, purchase.userData, purchase.totalPrice, abi.encodePacked(purchase.pricingData, purchase.paymentData, purchase.deliveryData) ); address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver; if (notificationsReceiver != address(0)) { require( IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived( purchase.purchaser, purchase.recipient, purchase.token, purchase.sku, purchase.quantity, purchase.userData, purchase.totalPrice, purchase.pricingData, purchase.paymentData, purchase.deliveryData ) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value "Sale: notification refused" ); } } } // File @animoca/ethereum-contracts-sale-2.0.0/contracts/sale/[email protected] pragma solidity >=0.7.6 <0.8.0; /** * @title FixedPricesSale * An Sale which implements a fixed prices strategy. * The final implementer is responsible for implementing any additional pricing and/or delivery logic. */ abstract contract FixedPricesSale is Sale { using ERC20Wrapper for IWrappedERC20; using SafeMath for uint256; using EnumMap for EnumMap.Map; /** * Constructor. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param payoutWallet_ the payout wallet. * @param skusCapacity the cap for the number of managed SKUs. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( address payable payoutWallet_, uint256 skusCapacity, uint256 tokensPerSkuCapacity ) Sale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {} /* Internal Life Cycle Functions */ /** * Lifecycle step which computes the purchase price. * @dev Responsibilities: * - Computes the pricing formula, including any discount logic and price conversion; * - Set the value of `purchase.totalPrice`; * - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it. * @dev Reverts if `purchase.sku` does not exist. * @dev Reverts if `purchase.token` is not supported by the SKU. * @dev Reverts in case of price overflow. * @param purchase The purchase conditions. */ function _pricing(PurchaseData memory purchase) internal view virtual override { SkuInfo storage skuInfo = _skuInfos[purchase.sku]; require(skuInfo.totalSupply != 0, "Sale: unsupported SKU"); EnumMap.Map storage prices = skuInfo.prices; uint256 unitPrice = _unitPrice(purchase, prices); purchase.totalPrice = unitPrice.mul(purchase.quantity); } /** * Lifecycle step which manages the transfer of funds from the purchaser. * @dev Responsibilities: * - Ensure the payment reaches destination in the expected output token; * - Handle any token swap logic; * - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it. * @dev Reverts in case of payment failure. * @param purchase The purchase conditions. */ function _payment(PurchaseData memory purchase) internal virtual override { if (purchase.token == TOKEN_ETH) { require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH"); payoutWallet.transfer(purchase.totalPrice); uint256 change = msg.value.sub(purchase.totalPrice); if (change != 0) { purchase.purchaser.transfer(change); } } else { IWrappedERC20(purchase.token).wrappedTransferFrom(_msgSender(), payoutWallet, purchase.totalPrice); } } /* Internal Utility Functions */ /** * Retrieves the unit price of a SKU for the specified payment token. * @dev Reverts if the specified payment token is unsupported. * @param purchase The purchase conditions specifying the payment token with which the unit price will be retrieved. * @param prices Storage pointer to a mapping of SKU token prices to retrieve the unit price from. * @return unitPrice The unit price of a SKU for the specified payment token. */ function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices) internal view virtual returns (uint256 unitPrice) { unitPrice = uint256(prices.get(bytes32(uint256(purchase.token)))); require(unitPrice != 0, "Sale: unsupported payment token"); } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/utils/[email protected] pragma solidity >=0.7.6 <0.8.0; abstract contract Recoverable is ManagedIdentity, Ownable { using ERC20Wrapper for IWrappedERC20; /** * Extract ERC20 tokens which were accidentally sent to the contract to a list of accounts. * Warning: this function should be overriden for contracts which are supposed to hold ERC20 tokens * so that the extraction is limited to only amounts sent accidentally. * @dev Reverts if the sender is not the contract owner. * @dev Reverts if `accounts`, `tokens` and `amounts` do not have the same length. * @dev Reverts if one of `tokens` is does not implement the ERC20 transfer function. * @dev Reverts if one of the ERC20 transfers fail for any reason. * @param accounts the list of accounts to transfer the tokens to. * @param tokens the list of ERC20 token addresses. * @param amounts the list of token amounts to transfer. */ function recoverERC20s( address[] calldata accounts, address[] calldata tokens, uint256[] calldata amounts ) external virtual { _requireOwnership(_msgSender()); uint256 length = accounts.length; require(length == tokens.length && length == amounts.length, "Recov: inconsistent arrays"); for (uint256 i = 0; i != length; ++i) { IWrappedERC20(tokens[i]).wrappedTransfer(accounts[i], amounts[i]); } } /** * Extract ERC721 tokens which were accidentally sent to the contract to a list of accounts. * Warning: this function should be overriden for contracts which are supposed to hold ERC721 tokens * so that the extraction is limited to only tokens sent accidentally. * @dev Reverts if the sender is not the contract owner. * @dev Reverts if `accounts`, `contracts` and `amounts` do not have the same length. * @dev Reverts if one of `contracts` is does not implement the ERC721 transferFrom function. * @dev Reverts if one of the ERC721 transfers fail for any reason. * @param accounts the list of accounts to transfer the tokens to. * @param contracts the list of ERC721 contract addresses. * @param tokenIds the list of token ids to transfer. */ function recoverERC721s( address[] calldata accounts, address[] calldata contracts, uint256[] calldata tokenIds ) external virtual { _requireOwnership(_msgSender()); uint256 length = accounts.length; require(length == contracts.length && length == tokenIds.length, "Recov: inconsistent arrays"); for (uint256 i = 0; i != length; ++i) { IRecoverableERC721(contracts[i]).transferFrom(address(this), accounts[i], tokenIds[i]); } } } interface IRecoverableERC721 { /// See {IERC721-transferFrom(address,address,uint256)} function transferFrom( address from, address to, uint256 tokenId ) external; } // File contracts/sale/TokenLaunchpadVoucherPacksSale.sol pragma solidity >=0.7.6 <0.8.0; /** * @title TokenLaunchpad Vouchers Sale * A FixedPricesSale contract that handles the purchase and delivery of TokenLaunchpad vouchers. */ contract TokenLaunchpadVoucherPacksSale is FixedPricesSale, Recoverable { IVouchersContract public immutable vouchersContract; struct SkuAdditionalInfo { uint256[] tokenIds; uint256 startTimestamp; uint256 endTimestamp; } mapping(bytes32 => SkuAdditionalInfo) internal _skuAdditionalInfo; /** * Constructor. * @dev Emits the `MagicValues` event. * @dev Emits the `Paused` event. * @param vouchersContract_ The inventory contract from which the sale supply is attributed from. * @param payoutWallet the payout wallet. * @param skusCapacity the cap for the number of managed SKUs. * @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU. */ constructor( IVouchersContract vouchersContract_, address payable payoutWallet, uint256 skusCapacity, uint256 tokensPerSkuCapacity ) FixedPricesSale(payoutWallet, skusCapacity, tokensPerSkuCapacity) { vouchersContract = vouchersContract_; } /** * Creates an SKU. * @dev Reverts if `totalSupply` is zero. * @dev Reverts if `sku` already exists. * @dev Reverts if the update results in too many SKUs. * @dev Reverts if one of `tokenIds` is not a fungible token identifier. * @dev Emits the `SkuCreation` event. * @param sku The SKU identifier. * @param totalSupply The initial total supply. * @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. * @param tokenIds The inventory contract token IDs to associate with the SKU, used for purchase delivery. * @param startTimestamp The start timestamp of the sale. * @param endTimestamp The end timestamp of the sale, or zero to indicate there is no end. */ function createSku( bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, uint256[] calldata tokenIds, uint256 startTimestamp, uint256 endTimestamp ) external { _requireOwnership(_msgSender()); uint256 length = tokenIds.length; require(length != 0, "Sale: empty tokens"); for (uint256 i; i != length; ++i) { require(vouchersContract.isFungible(tokenIds[i]), "Sale: not a fungible token"); } _skuAdditionalInfo[sku] = SkuAdditionalInfo(tokenIds, startTimestamp, endTimestamp); _createSku(sku, totalSupply, maxQuantityPerPurchase, address(0)); } /** * Updates start and end timestamps of a SKU. * @dev Reverts if not sent by the contract owner. * @dev Reverts if the SKU does not exist. * @param sku the SKU identifier. * @param startTimestamp The start timestamp of the sale. * @param endTimestamp The end timestamp of the sale, or zero to indicate there is no end. */ function updateSkuTimestamps( bytes32 sku, uint256 startTimestamp, uint256 endTimestamp ) external { _requireOwnership(_msgSender()); require(_skuInfos[sku].totalSupply != 0, "Sale: non-existent sku"); SkuAdditionalInfo storage info = _skuAdditionalInfo[sku]; info.startTimestamp = startTimestamp; info.endTimestamp = endTimestamp; } /** * Gets the additional sku info. * @dev Reverts if the SKU does not exist. * @param sku the SKU identifier. * @return tokenIds The identifiers of the tokens delivered via this SKU. * @return startTimestamp The start timestamp of the SKU sale. * @return endTimestamp The end timestamp of the SKU sale (zero if there is no end). */ function getSkuAdditionalInfo(bytes32 sku) external view returns ( uint256[] memory tokenIds, uint256 startTimestamp, uint256 endTimestamp ) { require(_skuInfos[sku].totalSupply != 0, "Sale: non-existent sku"); SkuAdditionalInfo memory info = _skuAdditionalInfo[sku]; return (info.tokenIds, info.startTimestamp, info.endTimestamp); } /** * Returns whether a SKU is currently within the sale time range. * @dev Reverts if the SKU does not exist. * @param sku the SKU identifier. * @return true if `sku` is currently within the sale time range, false otherwise. */ function canPurchaseSku(bytes32 sku) external view returns (bool) { require(_skuInfos[sku].totalSupply != 0, "Sale: non-existent sku"); SkuAdditionalInfo memory info = _skuAdditionalInfo[sku]; return block.timestamp > info.startTimestamp && (info.endTimestamp == 0 || block.timestamp < info.endTimestamp); } /// @inheritdoc Sale function _delivery(PurchaseData memory purchase) internal override { super._delivery(purchase); SkuAdditionalInfo memory info = _skuAdditionalInfo[purchase.sku]; uint256 startTimestamp = info.startTimestamp; uint256 endTimestamp = info.endTimestamp; require(block.timestamp > startTimestamp, "Sale: not started yet"); require(endTimestamp == 0 || block.timestamp < endTimestamp, "Sale: already ended"); uint256 length = info.tokenIds.length; if (length == 1) { vouchersContract.safeMint(purchase.recipient, info.tokenIds[0], purchase.quantity, ""); } else { uint256 purchaseQuantity = purchase.quantity; uint256[] memory quantities = new uint256[](length); for (uint256 i; i != length; ++i) { quantities[i] = purchaseQuantity; } vouchersContract.safeBatchMint(purchase.recipient, info.tokenIds, quantities, ""); } } } interface IVouchersContract { function isFungible(uint256 id) external pure returns (bool); function safeMint( address to, uint256 id, uint256 value, bytes calldata data ) external; function safeBatchMint( address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; }
solhint-disable-next-line avoid-low-level-calls revert using a standard revert message revert using the revert message coming from the call
function _callWithOptionalReturnData(IWrappedERC20 token, bytes memory callData) internal { address target = address(token); require(target.isContract(), "ERC20Wrapper: non-contract"); (bool success, bytes memory data) = target.call(callData); if (success) { if (data.length != 0) { require(abi.decode(data, (bool)), "ERC20Wrapper: operation failed"); } if (data.length == 0) { revert("ERC20Wrapper: operation failed"); } assembly { let size := mload(data) revert(add(32, data), size) } } }
2,077,468
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 4543, 17, 821, 17, 2815, 17, 12550, 15226, 1450, 279, 4529, 15226, 883, 15226, 1450, 326, 15226, 883, 19283, 628, 326, 745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1991, 1190, 6542, 990, 751, 12, 45, 17665, 654, 39, 3462, 1147, 16, 1731, 3778, 745, 751, 13, 2713, 288, 203, 3639, 1758, 1018, 273, 1758, 12, 2316, 1769, 203, 3639, 2583, 12, 3299, 18, 291, 8924, 9334, 315, 654, 39, 3462, 3611, 30, 1661, 17, 16351, 8863, 203, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1018, 18, 1991, 12, 1991, 751, 1769, 203, 3639, 309, 261, 4768, 13, 288, 203, 5411, 309, 261, 892, 18, 2469, 480, 374, 13, 288, 203, 7734, 2583, 12, 21457, 18, 3922, 12, 892, 16, 261, 6430, 13, 3631, 315, 654, 39, 3462, 3611, 30, 1674, 2535, 8863, 203, 5411, 289, 203, 5411, 309, 261, 892, 18, 2469, 422, 374, 13, 288, 203, 7734, 15226, 2932, 654, 39, 3462, 3611, 30, 1674, 2535, 8863, 203, 5411, 289, 203, 203, 5411, 19931, 288, 203, 7734, 2231, 963, 519, 312, 945, 12, 892, 13, 203, 7734, 15226, 12, 1289, 12, 1578, 16, 501, 3631, 963, 13, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x6BE60E29FBb7559A5aF18D1e8F840767dd315359/sources/tellorcore/contracts/TellorGetters.sol
* @dev Queries the balance of _user at a specific _blockNumber @param _user The address from which the balance will be retrieved @param _blockNumber The block number when the balance is queried @return The balance at _blockNumber/
function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256) { return tellor.balanceOfAt(_user, _blockNumber); }
817,626
[ 1, 9592, 326, 11013, 434, 389, 1355, 622, 279, 2923, 389, 2629, 1854, 225, 389, 1355, 1021, 1758, 628, 1492, 326, 11013, 903, 506, 10295, 225, 389, 2629, 1854, 1021, 1203, 1300, 1347, 326, 11013, 353, 23264, 327, 1021, 11013, 622, 389, 2629, 1854, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 861, 12, 2867, 389, 1355, 16, 2254, 5034, 389, 2629, 1854, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 9276, 280, 18, 12296, 951, 861, 24899, 1355, 16, 389, 2629, 1854, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "../library/openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../library/Pausable.sol"; import "../library/kip/IKIP7.sol"; import "../interface/IPoolToken.sol"; import "../interface/IBasePool.sol"; import "./StableSwap.sol"; /** * @dev BasePool is the solidity implementation of Curve Finance * Original code https://github.com/curvefi/curve-contract/blob/master/contracts/pools/3pool/StableSwap3Pool.vy */ abstract contract BasePool is IBasePool, StableSwap { // @dev WARN: be careful to add new variable here uint256[50] private __storageBuffer; constructor(uint256 _N) StableSwap(_N) {} /// @notice Contract initializer /// @param _coins Addresses of KIP7 contracts of coins /// @param _poolToken Address of the token representing LP share /// @param _initialA Amplification coefficient multiplied by n * (n - 1) /// @param _fee Fee to charge for exchanges /// @param _adminFee Admin fee function __BasePool_init( address[] memory _coins, uint256[] memory _PRECISION_MUL, uint256[] memory _RATES, address _poolToken, uint256 _initialA, uint256 _fee, uint256 _adminFee ) internal initializer { __StableSwap_init(_coins, _PRECISION_MUL, _RATES, _poolToken, _initialA, _fee, _adminFee); } function balances(uint256 i) public view override(II4ISwapPool, StableSwap) returns (uint256) { return _storedBalances[i]; } // 10**18 precision function _xp() internal view returns (uint256[] memory) { uint256[] memory result = new uint256[](N_COINS); for (uint256 i = 0; i < N_COINS; i++) { result[i] = (RATES[i] * _storedBalances[i]) / PRECISION; } return result; } // 10**18 precision function _xpMem(uint256[] memory _balances) internal view returns (uint256[] memory) { uint256[] memory result = new uint256[](N_COINS); for (uint256 i = 0; i < N_COINS; i++) { result[i] = (RATES[i] * _balances[i]) / PRECISION; } return result; } function getDMem(uint256[] memory _balances, uint256 amp) internal view returns (uint256) { return getD(_xpMem(_balances), amp); } function getVirtualPrice() external view override returns (uint256) { /* Returns portfolio virtual price (for calculating profit) scaled up by 1e18 */ uint256 D = getD(_xp(), _A()); // D is in the units similar to DAI (e.g. converted to precision 1e18) // When balanced, D = n * x_u - total virtual value of the portfolio uint256 tokenSupply = IPoolToken(token).totalSupply(); return (D * PRECISION) / tokenSupply; } /// @notice Simplified method to calculate addition or reduction in token supply at /// deposit or withdrawal without taking fees into account (but looking at /// slippage). /// Needed to prevent front-running, not for precise calculations! /// @param amounts amount list of each assets /// @param deposit the flag whether deposit or withdrawal /// @return the amount of lp tokens function calcTokenAmount(uint256[] memory amounts, bool deposit) external view override returns (uint256) { /* Simplified method to calculate addition or reduction in token supply at deposit or withdrawal without taking fees into account (but looking at slippage) . Needed to prevent front-running, not for precise calculations! */ uint256[] memory _balances = _storedBalances; uint256 amp = _A(); uint256 D0 = getDMem(_balances, amp); for (uint256 i = 0; i < N_COINS; i++) { if (deposit) { _balances[i] += amounts[i]; } else { _balances[i] -= amounts[i]; } } uint256 D1 = getDMem(_balances, amp); uint256 tokenAmount = IPoolToken(token).totalSupply(); uint256 diff = 0; if (deposit) { diff = D1 - D0; } else { diff = D0 - D1; } return (diff * tokenAmount) / D0; } function addLiquidity(uint256[] memory amounts, uint256 minMintAmount) external payable override nonReentrant whenNotPaused returns (uint256) { require(msg.value == 0); uint256 amp = _A(); uint256 tokenSupply = IPoolToken(token).totalSupply(); // Initial invariant uint256 D0 = 0; uint256[] memory oldBalances = _storedBalances; if (tokenSupply > 0) { D0 = getDMem(oldBalances, amp); } uint256[] memory newBalances = arrCopy(oldBalances); for (uint256 i = 0; i < N_COINS; i++) { uint256 inAmount = amounts[i]; if (tokenSupply == 0) { require(inAmount > 0); // dev: initial deposit requires all coins } address in_coin = coins[i]; // Take coins from the sender if (inAmount > 0) { // "safeTransferFrom" which works for KIP7s which return bool or not rawCall(in_coin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), amounts[i])); } newBalances[i] = oldBalances[i] + inAmount; } // Invariant after change uint256 D1 = getDMem(newBalances, amp); require(D1 > D0); // We need to recalculate the invariant accounting for fees // to calculate fair user's share uint256 D2 = D1; uint256[] memory fees = new uint256[](N_COINS); if (tokenSupply > 0) { // Only account for fees if we are not the first to deposit uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1)); uint256 _adminFee = adminFee; for (uint256 i = 0; i < N_COINS; i++) { uint256 idealBalance = (D1 * oldBalances[i]) / D0; uint256 difference = 0; if (idealBalance > newBalances[i]) { difference = idealBalance - newBalances[i]; } else { difference = newBalances[i] - idealBalance; } fees[i] = (_fee * difference) / FEE_DENOMINATOR; _storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR); newBalances[i] -= fees[i]; } D2 = getDMem(newBalances, amp); } else { _storedBalances = newBalances; } // Calculate, how much pool tokens to mint uint256 mintAmount = 0; if (tokenSupply == 0) { mintAmount = D1; // Take the dust if there was any } else { mintAmount = (tokenSupply * (D2 - D0)) / D0; } require(mintAmount >= minMintAmount, "Slippage screwed you"); // Mint pool tokens IPoolToken(token).mint(msg.sender, mintAmount); emit AddLiquidity(msg.sender, amounts, fees, D1, tokenSupply + mintAmount); return mintAmount; } function _getDy( uint256 i, uint256 j, uint256 dx, bool withoutFee ) internal view override returns (uint256) { // dx and dy in c-units uint256[] memory xp = _xp(); uint256 x = xp[i] + ((dx * RATES[i]) / PRECISION); uint256 y = getY(i, j, x, xp); uint256 dy = ((xp[j] - y - 1) * PRECISION) / RATES[j]; uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR; return dy - _fee; } // reference: https://github.com/curvefi/curve-contract/blob/c6df0cf14b557b11661a474d8d278affd849d3fe/contracts/pools/y/StableSwapY.vy#L351 function _getDx( uint256 i, uint256 j, uint256 dy ) internal view override returns (uint256) { uint256[] memory xp = _xp(); uint256 y = xp[j] - (((dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - fee)) * RATES[j]) / PRECISION; uint256 x = getY(j, i, y, xp); uint256 dx = ((x - xp[i]) * PRECISION) / RATES[i]; return dx; } function _getDyUnderlying( uint256 i, uint256 j, uint256 dx, bool withoutFee ) internal view override returns (uint256) { // dx and dy in underlying units uint256[] memory xp = _xp(); uint256 x = xp[i] + dx * PRECISION_MUL[i]; uint256 y = getY(i, j, x, xp); uint256 dy = (xp[j] - y - 1) / PRECISION_MUL[j]; uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR; return dy - _fee; } function exchange( uint256 i, uint256 j, uint256 dx, uint256 minDy ) external payable override nonReentrant whenNotPaused returns (uint256) { require(msg.value == 0); uint256[] memory oldBalances = _storedBalances; uint256[] memory xp = _xpMem(oldBalances); address inputCoin = coins[i]; // "safeTransferFrom" which works for KIP7s which return bool or not rawCall(inputCoin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), dx)); uint256 x = xp[i] + (dx * RATES[i]) / PRECISION; uint256 y = getY(i, j, x, xp); uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors uint256 dyFee = (dy * fee) / FEE_DENOMINATOR; // Convert all to real units dy = ((dy - dyFee) * PRECISION) / RATES[j]; require(dy >= minDy, "Exchange resulted in fewer coins than expected"); uint256 dyAdminFee = (dyFee * adminFee) / FEE_DENOMINATOR; dyAdminFee = (dyAdminFee * PRECISION) / RATES[j]; // Change balances exactly in same way as we change actual KIP7 coin amounts _storedBalances[i] = oldBalances[i] + dx; // When rounding errors happen, we undercharge admin fee in favor of LP _storedBalances[j] = oldBalances[j] - dy - dyAdminFee; // "safeTransfer" which works for KIP7s which return bool or not rawCall(coins[j], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy)); emit TokenExchange(msg.sender, i, dx, j, dy, dyFee); return dy; } /// @notice Withdraw coins from the pool /// @dev Withdrawal amounts are based on current deposit ratios /// @param _amount Quantity of LP tokens to burn in the withdrawal /// @param minAmounts Minimum amounts of underlying coins to receive /// @return List of amounts of coins that were withdrawn function removeLiquidity(uint256 _amount, uint256[] memory minAmounts) external override nonReentrant returns (uint256[] memory) { uint256 totalSupply = IPoolToken(token).totalSupply(); uint256[] memory amounts = new uint256[](N_COINS); uint256[] memory fees = new uint256[](N_COINS); // Fees are unused but we've got them historically in event for (uint256 i = 0; i < N_COINS; i++) { uint256 value = (_storedBalances[i] * _amount) / totalSupply; require(value >= minAmounts[i], "Withdrawal resulted in fewer coins than expected"); _storedBalances[i] -= value; amounts[i] = value; // "safeTransfer" which works for KIP7s which return bool or not rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, value)); } IPoolToken(token).burn(msg.sender, _amount); // dev: insufficient funds emit RemoveLiquidity(msg.sender, amounts, fees, totalSupply - _amount); return amounts; } function removeLiquidityImbalance(uint256[] memory amounts, uint256 maxBurnAmount) external override nonReentrant whenNotPaused returns (uint256) { uint256 tokenSupply = IPoolToken(token).totalSupply(); require(tokenSupply != 0); // dev: zero total supply uint256 amp = _A(); uint256[] memory oldBalances = _storedBalances; uint256[] memory newBalances = arrCopy(oldBalances); uint256 D0 = getDMem(oldBalances, amp); for (uint256 i = 0; i < N_COINS; i++) { newBalances[i] -= amounts[i]; } uint256 D1 = getDMem(newBalances, amp); uint256[] memory fees = new uint256[](N_COINS); { uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1)); uint256 _adminFee = adminFee; for (uint256 i = 0; i < N_COINS; i++) { uint256 idealBalance = (D1 * oldBalances[i]) / D0; uint256 difference = 0; if (idealBalance > newBalances[i]) { difference = idealBalance - newBalances[i]; } else { difference = newBalances[i] - idealBalance; } fees[i] = (_fee * difference) / FEE_DENOMINATOR; _storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR); newBalances[i] -= fees[i]; } } uint256 D2 = getDMem(newBalances, amp); uint256 tokenAmount = ((D0 - D2) * tokenSupply) / D0; require(tokenAmount != 0); // dev: zero tokens burned tokenAmount += 1; // In case of rounding errors - make it unfavorable for the "attacker" require(tokenAmount <= maxBurnAmount, "Slippage screwed you"); IPoolToken(token).burn(msg.sender, tokenAmount); // dev: insufficient funds for (uint256 i = 0; i < N_COINS; i++) { if (amounts[i] != 0) { // "safeTransfer" which works for KIP7s which return bool or not rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, amounts[i])); } } emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, tokenSupply - tokenAmount); return tokenAmount; } function _calcWithdrawOneCoin( uint256 _tokenAmount, uint256 i, bool withoutFee ) internal view returns ( uint256, uint256, uint256 ) { // First, need to calculate // * Get current D // * Solve Eqn against y_i for D - _tokenAmount uint256 amp = _A(); uint256 totalSupply = IPoolToken(token).totalSupply(); uint256[] memory xp = _xp(); uint256 D0 = getD(xp, amp); uint256 D1 = D0 - (_tokenAmount * D0) / totalSupply; uint256[] memory xpReduced = arrCopy(xp); uint256 newY = getYD(amp, i, xp, D1); uint256 dy0 = (xp[i] - newY) / PRECISION_MUL[i]; // w/o fees, precision depends on coin { uint256 _fee = ((withoutFee ? 0 : fee) * N_COINS) / (4 * (N_COINS - 1)); for (uint256 j = 0; j < N_COINS; j++) { uint256 dxExpected = 0; if (j == i) { dxExpected = (xp[j] * D1) / D0 - newY; } else { dxExpected = xp[j] - (xp[j] * D1) / D0; // 10**18 } xpReduced[j] -= (_fee * dxExpected) / FEE_DENOMINATOR; } } uint256 dy = xpReduced[i] - getYD(amp, i, xpReduced, D1); dy = (dy - 1) / PRECISION_MUL[i]; // Withdraw less to account for rounding errors return (dy, dy0 - dy, totalSupply); } function calcWithdrawOneCoin(uint256 _tokenAmount, uint256 i) external view override returns (uint256) { (uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, false); return result; } function calcWithdrawOneCoinWithoutFee(uint256 _tokenAmount, uint256 i) external view override returns (uint256) { (uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, true); return result; } function removeLiquidityOneCoin( uint256 _tokenAmount, uint256 i, uint256 minAmount ) external override nonReentrant whenNotPaused returns (uint256) { /* Remove _amount of liquidity all in a form of coin i */ (uint256 dy, uint256 dyFee, uint256 totalSupply) = _calcWithdrawOneCoin(_tokenAmount, i, false); require(dy >= minAmount, "Not enough coins removed"); _storedBalances[i] -= (dy + (dyFee * adminFee) / FEE_DENOMINATOR); IPoolToken(token).burn(msg.sender, _tokenAmount); // dev: insufficient funds // "safeTransfer" which works for KIP7s which return bool or not rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy)); uint256[] memory amounts = new uint256[](N_COINS); uint256[] memory fees = new uint256[](N_COINS); amounts[i] = dy; fees[i] = dyFee; emit RemoveLiquidityOne(msg.sender, _tokenAmount, amounts, fees, totalSupply - _tokenAmount); return dy; } function transferOwnership(address newOwner) public override(IStableSwap, StableSwap) onlyOwner { super.transferOwnership(newOwner); } function adminBalances(uint256 i) public view override(IStableSwap, StableSwap) returns (uint256) { return IKIP7(coins[i]).balanceOf(address(this)) - _storedBalances[i]; } function withdrawAdminFees(address recipient) external override onlyOperator { require(recipient != address(0), "StableSwap::withdrawAdminFee: 0 address"); for (uint256 i = 0; i < N_COINS; i++) { address c = coins[i]; uint256 value = IKIP7(c).balanceOf(address(this)) - _storedBalances[i]; if (value > 0) { // "safeTransfer" which works for KIP7s which return bool or not rawCall(c, abi.encodeWithSignature("transfer(address,uint256)", recipient, value)); } } } function donateAdminFees() external override onlyOwner { for (uint256 i = 0; i < N_COINS; i++) { _storedBalances[i] = IKIP7(coins[i]).balanceOf(address(this)); } } }
D is in the units similar to DAI (e.g. converted to precision 1e18) When balanced, D = n * x_u - total virtual value of the portfolio
function getVirtualPrice() external view override returns (uint256) { Returns portfolio virtual price (for calculating profit) scaled up by 1e18 uint256 D = getD(_xp(), _A()); uint256 tokenSupply = IPoolToken(token).totalSupply(); return (D * PRECISION) / tokenSupply; }
1,022,100
[ 1, 40, 353, 316, 326, 4971, 7281, 358, 463, 18194, 261, 73, 18, 75, 18, 5970, 358, 6039, 404, 73, 2643, 13, 5203, 11013, 72, 16, 463, 273, 290, 225, 619, 67, 89, 300, 2078, 5024, 460, 434, 326, 19933, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 6466, 5147, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2860, 19933, 5024, 6205, 261, 1884, 21046, 450, 7216, 13, 203, 3639, 12304, 731, 635, 404, 73, 2643, 203, 3639, 2254, 5034, 463, 273, 2343, 24899, 23829, 9334, 389, 37, 10663, 203, 3639, 2254, 5034, 1147, 3088, 1283, 273, 467, 2864, 1345, 12, 2316, 2934, 4963, 3088, 1283, 5621, 203, 3639, 327, 261, 40, 380, 7071, 26913, 13, 342, 1147, 3088, 1283, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/40/0x25cA003E9a68B3540D19a071DAcC740D56CD752f/sources/contracts/XpandrVaultV1.sol
Entrypoint of funds into the system. The vault then deposits funds into the strategy.
function deposit(uint _amount) public nonReentrant { require(_amount > 0, "< 0"); strategy.beforeDeposit(); uint256 _pool = balance(); want().safeTransferFrom(msg.sender, address(this), _amount); _earn(); uint256 _after = balance(); uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; shares = (_amount * totalSupply()) / _pool; } _mint(msg.sender, shares); }
9,545,170
[ 1, 1622, 1153, 434, 284, 19156, 1368, 326, 2619, 18, 1021, 9229, 1508, 443, 917, 1282, 284, 19156, 1368, 326, 6252, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 389, 8949, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 3532, 374, 8863, 203, 3639, 6252, 18, 5771, 758, 1724, 5621, 203, 3639, 2254, 5034, 389, 6011, 273, 11013, 5621, 203, 3639, 2545, 7675, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 389, 73, 1303, 5621, 203, 3639, 2254, 5034, 389, 5205, 273, 11013, 5621, 203, 3639, 2254, 5034, 24123, 273, 374, 31, 203, 3639, 309, 261, 4963, 3088, 1283, 1435, 422, 374, 13, 288, 203, 5411, 24123, 273, 389, 8949, 31, 203, 5411, 24123, 273, 261, 67, 8949, 380, 2078, 3088, 1283, 10756, 342, 389, 6011, 31, 203, 3639, 289, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 24123, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic authorization control functions, /// this simplifies the implementation of "user permissions". /// @dev Based on OpenZeppelin's Ownable. contract Ownable { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed _by, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); /// @dev Constructor sets the original `owner` of the contract to the sender account. function Ownable() public { owner = msg.sender; } /// @dev Reverts if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOwnerCandidate() { require(msg.sender == newOwnerCandidate); _; } /// @dev Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { require(_newOwnerCandidate != address(0)); newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner. function acceptOwnership() external onlyOwnerCandidate { address previousOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(previousOwner, owner); } } /// @title Math operations with safety checks library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function toPower2(uint256 a) internal pure returns (uint256) { return mul(a, a); } function sqrt(uint256 a) internal pure returns (uint256) { uint256 c = (a + 1) / 2; uint256 b = a; while (c < b) { b = c; c = (a / c + c) / 2; } return b; } } /// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) contract ERC20 { uint public totalSupply; function balanceOf(address _owner) constant public returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677) contract ERC677 is ERC20 { function transferAndCall(address to, uint value, bytes data) public returns (bool ok); event TransferAndCall(address indexed from, address indexed to, uint value, bytes data); } /// @title ERC223Receiver Interface /// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223 contract ERC223Receiver { function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); } /// @title Basic ERC20 token contract implementation. /// @dev Based on OpenZeppelin's StandardToken. contract BasicToken is ERC20 { using SafeMath for uint256; uint256 public totalSupply; mapping (address => mapping (address => uint256)) allowed; mapping (address => uint256) balances; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public returns (bool) { // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE) if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Function to check the amount of tokens that an owner allowed to a spender. /// @param _owner address The address which owns the funds. /// @param _spender address The address which will spend the funds. /// @return uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Gets the balance of the specified address. /// @param _owner address The address to query the the balance of. /// @return uint256 representing the amount owned by the passed address. function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } /// @dev Transfer token to a specified address. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Transfer tokens from one address to another. /// @param _from address The address which you want to send tokens from. /// @param _to address The address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } } /// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677 contract Standard677Token is ERC677, BasicToken { /// @dev ERC223 safe token transfer from one address to another /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) { require(super.transfer(_to, _value)); // do a normal token transfer TransferAndCall(msg.sender, _to, _value, _data); //filtering if the target is a contract with bytecode inside it if (isContract(_to)) return contractFallback(_to, _value, _data); return true; } /// @dev called when transaction target is a contract /// @param _to address the address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function contractFallback(address _to, uint _value, bytes _data) private returns (bool) { ERC223Receiver receiver = ERC223Receiver(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); return true; } /// @dev check if the address is contract /// assemble the given address bytecode. If bytecode exists then the _addr is a contract. /// @param _addr address the address to check function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } } /// @title Token holder contract. contract TokenHolder is Ownable { /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); } } /// @title Colu Local Network contract. /// @author Tal Beja. contract ColuLocalNetwork is Ownable, Standard677Token, TokenHolder { using SafeMath for uint256; string public constant name = "Colu Local Network"; string public constant symbol = "CLN"; // Using same decimals value as ETH (makes ETH-CLN conversion much easier). uint8 public constant decimals = 18; // States whether token transfers is allowed or not. // Used during token sale. bool public isTransferable = false; event TokensTransferable(); modifier transferable() { require(msg.sender == owner || isTransferable); _; } /// @dev Creates all tokens and gives them to the owner. function ColuLocalNetwork(uint256 _totalSupply) public { totalSupply = _totalSupply; balances[msg.sender] = totalSupply; } /// @dev start transferable mode. function makeTokensTransferable() external onlyOwner { if (isTransferable) { return; } isTransferable = true; TokensTransferable(); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public transferable returns (bool) { return super.approve(_spender, _value); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public transferable returns (bool) { return super.transfer(_to, _value); } /// @dev Same ERC20 behavior, but reverts if not transferable. /// @param _from address The address to send tokens from. /// @param _to address The address to transfer to. /// @param _value uint256 the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) { return super.transferFrom(_from, _to, _value); } /// @dev Same ERC677 behavior, but reverts if not transferable. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. /// @param _data bytes data to send to receiver if it is a contract. function transferAndCall(address _to, uint _value, bytes _data) public transferable returns (bool success) { return super.transferAndCall(_to, _value, _data); } } /// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier contract Standard223Receiver is ERC223Receiver { Tkn tkn; struct Tkn { address addr; address sender; // the transaction caller uint256 value; } bool __isTokenFallback; modifier tokenPayable { require(__isTokenFallback); _; } /// @dev Called when the receiver of transfer is contract /// @param _sender address the address of tokens sender /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { if (!supportsToken(msg.sender)) { return false; } // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory. // Solution: Remove the the data tkn = Tkn(msg.sender, _sender, _value); __isTokenFallback = true; if (!address(this).delegatecall(_data)) { __isTokenFallback = false; return false; } // avoid doing an overwrite to .token, which would be more expensive // makes accessing .tkn values outside tokenPayable functions unsafe __isTokenFallback = false; return true; } function supportsToken(address token) public constant returns (bool); } /// @title TokenOwnable /// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation contract TokenOwnable is Standard223Receiver, Ownable { /// @dev Reverts if called by any account other than the owner for token sending. modifier onlyTokenOwner() { require(tkn.sender == owner); _; } } /// @title Vesting trustee contract for Colu Local Network. /// @dev This Contract can't be TokenHolder, since it will allow its owner to drain its vested tokens. /// @dev This means that any token sent to it different than ColuLocalNetwork is basicly stucked here forever. /// @dev ColuLocalNetwork that sent here (by mistake) can withdrawn using the grant method. contract VestingTrustee is TokenOwnable { using SafeMath for uint256; // Colu Local Network contract. ColuLocalNetwork public cln; // Vesting grant for a speicifc holder. struct Grant { uint256 value; uint256 start; uint256 cliff; uint256 end; uint256 installmentLength; // In seconds. uint256 transferred; bool revokable; } // Holder to grant information mapping. mapping (address => Grant) public grants; // Total tokens vested. uint256 public totalVesting; event NewGrant(address indexed _from, address indexed _to, uint256 _value); event TokensUnlocked(address indexed _to, uint256 _value); event GrantRevoked(address indexed _holder, uint256 _refund); uint constant OK = 1; uint constant ERR_INVALID_VALUE = 10001; uint constant ERR_INVALID_VESTED = 10002; uint constant ERR_INVALID_TRANSFERABLE = 10003; event Error(address indexed sender, uint error); /// @dev Constructor that initializes the address of the Colu Local Network contract. /// @param _cln ColuLocalNetwork The address of the previously deployed Colu Local Network contract. function VestingTrustee(ColuLocalNetwork _cln) public { require(_cln != address(0)); cln = _cln; } /// @dev Allow only cln token to be tokenPayable /// @param token the token to check function supportsToken(address token) public constant returns (bool) { return (cln == token); } /// @dev Grant tokens to a specified address. /// @param _to address The holder address. /// @param _start uint256 The beginning of the vesting period (timestamp). /// @param _cliff uint256 When the first installment is made (timestamp). /// @param _end uint256 The end of the vesting period (timestamp). /// @param _installmentLength uint256 The length of each vesting installment (in seconds). /// @param _revokable bool Whether the grant is revokable or not. function grant(address _to, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) external onlyTokenOwner tokenPayable { require(_to != address(0)); require(_to != address(this)); // Protect this contract from receiving a grant. uint256 value = tkn.value; require(value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Require for time ranges to be consistent and valid. require(_start <= _cliff && _cliff <= _end); // Require installment length to be valid and no longer than (end - start). require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); // Grant must not exceed the total amount of tokens currently available for vesting. require(totalVesting.add(value) <= cln.balanceOf(address(this))); // Assign a new grant. grants[_to] = Grant({ value: value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revokable: _revokable }); // Since tokens have been granted, increase the total amount vested. totalVesting = totalVesting.add(value); NewGrant(msg.sender, _to, value); } /// @dev Grant tokens to a specified address. /// @param _to address The holder address. /// @param _value uint256 The amount of tokens to be granted. /// @param _start uint256 The beginning of the vesting period (timestamp). /// @param _cliff uint256 When the first installment is made (timestamp). /// @param _end uint256 The end of the vesting period (timestamp). /// @param _installmentLength uint256 The length of each vesting installment (in seconds). /// @param _revokable bool Whether the grant is revokable or not. function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) external onlyOwner { require(_to != address(0)); require(_to != address(this)); // Protect this contract from receiving a grant. require(_value > 0); // Require that every holder can be granted tokens only once. require(grants[_to].value == 0); // Require for time ranges to be consistent and valid. require(_start <= _cliff && _cliff <= _end); // Require installment length to be valid and no longer than (end - start). require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); // Grant must not exceed the total amount of tokens currently available for vesting. require(totalVesting.add(_value) <= cln.balanceOf(address(this))); // Assign a new grant. grants[_to] = Grant({ value: _value, start: _start, cliff: _cliff, end: _end, installmentLength: _installmentLength, transferred: 0, revokable: _revokable }); // Since tokens have been granted, increase the total amount vested. totalVesting = totalVesting.add(_value); NewGrant(msg.sender, _to, _value); } /// @dev Revoke the grant of tokens of a specifed address. /// @dev Unlocked tokens will be sent to the grantee, the rest is transferred to the trustee's owner. /// @param _holder The address which will have its tokens revoked. function revoke(address _holder) public onlyOwner { Grant memory grant = grants[_holder]; // Grant must be revokable. require(grant.revokable); // Get the total amount of vested tokens, acccording to grant. uint256 vested = calculateVestedTokens(grant, now); // Calculate the untransferred vested tokens. uint256 transferable = vested.sub(grant.transferred); if (transferable > 0) { // Update transferred and total vesting amount, then transfer remaining vested funds to holder. grant.transferred = grant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); require(cln.transfer(_holder, transferable)); TokensUnlocked(_holder, transferable); } // Calculate amount of remaining tokens that can still be returned. uint256 refund = grant.value.sub(grant.transferred); // Remove the grant. delete grants[_holder]; // Update total vesting amount and transfer previously calculated tokens to owner. totalVesting = totalVesting.sub(refund); require(cln.transfer(msg.sender, refund)); GrantRevoked(_holder, refund); } /// @dev Calculate the amount of ready tokens of a holder. /// @param _holder address The address of the holder. /// @return a uint256 Representing a holder's total amount of vested tokens. function readyTokens(address _holder) public constant returns (uint256) { Grant memory grant = grants[_holder]; if (grant.value == 0) { return 0; } uint256 vested = calculateVestedTokens(grant, now); if (vested == 0) { return 0; } return vested.sub(grant.transferred); } /// @dev Calculate the total amount of vested tokens of a holder at a given time. /// @param _holder address The address of the holder. /// @param _time uint256 The specific time to calculate against. /// @return a uint256 Representing a holder's total amount of vested tokens. function vestedTokens(address _holder, uint256 _time) public constant returns (uint256) { Grant memory grant = grants[_holder]; if (grant.value == 0) { return 0; } return calculateVestedTokens(grant, _time); } /// @dev Calculate amount of vested tokens at a specifc time. /// @param _grant Grant The vesting grant. /// @param _time uint256 The time to be checked /// @return An uint256 Representing the amount of vested tokens of a specific grant. function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) { // If we're before the cliff, then nothing is vested. if (_time < _grant.cliff) { return 0; } // If we're after the end of the vesting period - everything is vested. if (_time >= _grant.end) { return _grant.value; } // Calculate amount of installments past until now. // // NOTE: result gets floored because of integer division. uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength); // Calculate amount of days in entire vesting period. uint256 vestingDays = _grant.end.sub(_grant.start); // Calculate and return the number of tokens according to vesting days that have passed. return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays); } /// @dev Unlock vested tokens and transfer them to the grantee. /// @return a uint The success or error code. function unlockVestedTokens() external returns (uint) { return unlockVestedTokens(msg.sender); } /// @dev Unlock vested tokens and transfer them to the grantee (helper function). /// @param _grantee address The address of the grantee. /// @return a uint The success or error code. function unlockVestedTokens(address _grantee) private returns (uint) { Grant storage grant = grants[_grantee]; // Make sure the grant has tokens available. if (grant.value == 0) { Error(_grantee, ERR_INVALID_VALUE); return ERR_INVALID_VALUE; } // Get the total amount of vested tokens, acccording to grant. uint256 vested = calculateVestedTokens(grant, now); if (vested == 0) { Error(_grantee, ERR_INVALID_VESTED); return ERR_INVALID_VESTED; } // Make sure the holder doesn't transfer more than what he already has. uint256 transferable = vested.sub(grant.transferred); if (transferable == 0) { Error(_grantee, ERR_INVALID_TRANSFERABLE); return ERR_INVALID_TRANSFERABLE; } // Update transferred and total vesting amount, then transfer remaining vested funds to holder. grant.transferred = grant.transferred.add(transferable); totalVesting = totalVesting.sub(transferable); require(cln.transfer(_grantee, transferable)); TokensUnlocked(_grantee, transferable); return OK; } /// @dev batchUnlockVestedTokens vested tokens and transfer them to the grantees. /// @param _grantees address[] The addresses of the grantees. /// @return a boo if success. function batchUnlockVestedTokens(address[] _grantees) external onlyOwner returns (bool success) { for (uint i = 0; i<_grantees.length; i++) { unlockVestedTokens(_grantees[i]); } return true; } /// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. /// @param _tokenAddress address The address of the ERC20 contract. /// @param _amount uint256 The amount of tokens to be transferred. function withdrawERC20(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { if (_tokenAddress == address(cln)) { // If the token is cln, allow to withdraw only non vested tokens. uint256 availableCLN = cln.balanceOf(this).sub(totalVesting); require(_amount <= availableCLN); } return ERC20(_tokenAddress).transfer(owner, _amount); } } /// @title Colu Local Network sale contract. /// @author Tal Beja. contract ColuLocalNetworkSale is Ownable, TokenHolder { using SafeMath for uint256; // External parties: // Colu Local Network contract. ColuLocalNetwork public cln; // Vesting contract for presale participants. VestingTrustee public trustee; // Received funds are forwarded to this address. address public fundingRecipient; // Post-TDE multisig addresses. address public communityPoolAddress; address public futureDevelopmentPoolAddress; address public stakeholdersPoolAddress; // Colu Local Network decimals. // Using same decimals value as ETH (makes ETH-CLN conversion much easier). // This is the same as in Colu Local Network contract. uint256 public constant TOKEN_DECIMALS = 10 ** 18; // Additional Lockup Allocation Pool uint256 public constant ALAP = 40701333592592592592614116; // Maximum number of tokens in circulation: 1.5 trillion. uint256 public constant MAX_TOKENS = 15 * 10 ** 8 * TOKEN_DECIMALS + ALAP; // Maximum tokens offered in the sale (35%) + ALAP. uint256 public constant MAX_TOKENS_SOLD = 525 * 10 ** 6 * TOKEN_DECIMALS + ALAP; // Maximum tokens offered in the presale (from the initial 35% offered tokens) + ALAP. uint256 public constant MAX_PRESALE_TOKENS_SOLD = 2625 * 10 ** 5 * TOKEN_DECIMALS + ALAP; // Tokens allocated for Community pool (30%). uint256 public constant COMMUNITY_POOL = 45 * 10 ** 7 * TOKEN_DECIMALS; // Tokens allocated for Future development pool (29%). uint256 public constant FUTURE_DEVELOPMENT_POOL = 435 * 10 ** 6 * TOKEN_DECIMALS; // Tokens allocated for Stakeholdes pool (6%). uint256 public constant STAKEHOLDERS_POOL = 9 * 10 ** 7 * TOKEN_DECIMALS; // CLN to ETH ratio. uint256 public constant CLN_PER_ETH = 8600; // Sale start, end blocks (time ranges) uint256 public constant SALE_DURATION = 4 days; uint256 public startTime; uint256 public endTime; // Amount of tokens sold until now in the sale. uint256 public tokensSold = 0; // Amount of tokens sold until now in the presale. uint256 public presaleTokensSold = 0; // Accumulated amount each participant has contributed so far in the sale (in WEI). mapping (address => uint256) public participationHistory; // Accumulated amount each participant have contributed so far in the presale. mapping (address => uint256) public participationPresaleHistory; // Maximum amount that each particular is allowed to contribute (in ETH-WEI). // Defaults to zero. Serving as a functional whitelist. mapping (address => uint256) public participationCaps; // Maximum amount ANYONE is currently allowed to contribute. Set to max uint256 so no limitation other than personal participationCaps. uint256 public hardParticipationCap = uint256(-1); // initialization of the contract, splitted from the constructor to avoid gas block limit. bool public initialized = false; // Vesting plan structure for presale struct VestingPlan { uint256 startOffset; uint256 cliffOffset; uint256 endOffset; uint256 installmentLength; uint8 alapPercent; } // Vesting plans for presale VestingPlan[] public vestingPlans; // Each token that is sent from the ColuLocalNetworkSale is considered as issued. event TokensIssued(address indexed to, uint256 tokens); /// @dev Reverts if called not before the sale. modifier onlyBeforeSale() { if (now >= startTime) { revert(); } _; } /// @dev Reverts if called not during the sale. modifier onlyDuringSale() { if (tokensSold >= MAX_TOKENS_SOLD || now < startTime || now >= endTime) { revert(); } _; } /// @dev Reverts if called before the sale ends. modifier onlyAfterSale() { if (!(tokensSold >= MAX_TOKENS_SOLD || now >= endTime)) { revert(); } _; } /// @dev Reverts if called before the sale is initialized. modifier notInitialized() { if (initialized) { revert(); } _; } /// @dev Reverts if called after the sale is initialized. modifier isInitialized() { if (!initialized) { revert(); } _; } /// @dev Constructor sets the sale addresses and start time. /// @param _owner address The address of this contract owner. /// @param _fundingRecipient address The address of the funding recipient. /// @param _communityPoolAddress address The address of the community pool. /// @param _futureDevelopmentPoolAddress address The address of the future development pool. /// @param _stakeholdersPoolAddress address The address of the team pool. /// @param _startTime uint256 The start time of the token sale. function ColuLocalNetworkSale(address _owner, address _fundingRecipient, address _communityPoolAddress, address _futureDevelopmentPoolAddress, address _stakeholdersPoolAddress, uint256 _startTime) public { require(_owner != address(0)); require(_fundingRecipient != address(0)); require(_communityPoolAddress != address(0)); require(_futureDevelopmentPoolAddress != address(0)); require(_stakeholdersPoolAddress != address(0)); require(_startTime > now); owner = _owner; fundingRecipient = _fundingRecipient; communityPoolAddress = _communityPoolAddress; futureDevelopmentPoolAddress = _futureDevelopmentPoolAddress; stakeholdersPoolAddress = _stakeholdersPoolAddress; startTime = _startTime; endTime = startTime + SALE_DURATION; } /// @dev Initialize the sale conditions. function initialize() public onlyOwner notInitialized { initialized = true; uint256 months = 1 years / 12; vestingPlans.push(VestingPlan(0, 0, 1, 1, 0)); vestingPlans.push(VestingPlan(0, 0, 6 * months, 1 * months, 4)); vestingPlans.push(VestingPlan(0, 0, 1 years, 1 * months, 12)); vestingPlans.push(VestingPlan(0, 0, 2 years, 1 * months, 26)); vestingPlans.push(VestingPlan(0, 0, 3 years, 1 * months, 35)); // Deploy new ColuLocalNetwork contract. cln = new ColuLocalNetwork(MAX_TOKENS); // Deploy new VestingTrustee contract. trustee = new VestingTrustee(cln); // allocate pool tokens: // Issue the remaining tokens to designated pools. require(transferTokens(communityPoolAddress, COMMUNITY_POOL)); // stakeholdersPoolAddress will create its own vesting trusts. require(transferTokens(stakeholdersPoolAddress, STAKEHOLDERS_POOL)); } /// @dev Allocate tokens to presale participant according to its vesting plan and invesment value. /// @param _recipient address The presale participant address to recieve the tokens. /// @param _etherValue uint256 The invesment value (in ETH). /// @param _vestingPlanIndex uint8 The vesting plan index. function presaleAllocation(address _recipient, uint256 _etherValue, uint8 _vestingPlanIndex) external onlyOwner onlyBeforeSale isInitialized { require(_recipient != address(0)); require(_vestingPlanIndex < vestingPlans.length); // Calculate plan and token amount. VestingPlan memory plan = vestingPlans[_vestingPlanIndex]; uint256 tokensAndALAPPerEth = CLN_PER_ETH.mul(SafeMath.add(100, plan.alapPercent)).div(100); uint256 tokensLeftInPreSale = MAX_PRESALE_TOKENS_SOLD.sub(presaleTokensSold); uint256 weiLeftInSale = tokensLeftInPreSale.div(tokensAndALAPPerEth); uint256 weiToParticipate = SafeMath.min256(_etherValue, weiLeftInSale); require(weiToParticipate > 0); participationPresaleHistory[msg.sender] = participationPresaleHistory[msg.sender].add(weiToParticipate); uint256 tokensToTransfer = weiToParticipate.mul(tokensAndALAPPerEth); presaleTokensSold = presaleTokensSold.add(tokensToTransfer); tokensSold = tokensSold.add(tokensToTransfer); // Transfer tokens to trustee and create grant. grant(_recipient, tokensToTransfer, startTime.add(plan.startOffset), startTime.add(plan.cliffOffset), startTime.add(plan.endOffset), plan.installmentLength, false); } /// @dev Add a list of participants to a capped participation tier. /// @param _participants address[] The list of participant addresses. /// @param _cap uint256 The cap amount (in ETH-WEI). function setParticipationCap(address[] _participants, uint256 _cap) external onlyOwner isInitialized { for (uint i = 0; i < _participants.length; i++) { participationCaps[_participants[i]] = _cap; } } /// @dev Set hard participation cap for all participants. /// @param _cap uint256 The hard cap amount. function setHardParticipationCap(uint256 _cap) external onlyOwner isInitialized { require(_cap > 0); hardParticipationCap = _cap; } /// @dev Fallback function that will delegate the request to participate(). function () external payable onlyDuringSale isInitialized { participate(msg.sender); } /// @dev Create and sell tokens to the caller. /// @param _recipient address The address of the recipient receiving the tokens. function participate(address _recipient) public payable onlyDuringSale isInitialized { require(_recipient != address(0)); // Enforce participation cap (in WEI received). uint256 weiAlreadyParticipated = participationHistory[_recipient]; uint256 participationCap = SafeMath.min256(participationCaps[_recipient], hardParticipationCap); uint256 cappedWeiReceived = SafeMath.min256(msg.value, participationCap.sub(weiAlreadyParticipated)); require(cappedWeiReceived > 0); // Accept funds and transfer to funding recipient. uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold); uint256 weiLeftInSale = tokensLeftInSale.div(CLN_PER_ETH); uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale); participationHistory[_recipient] = weiAlreadyParticipated.add(weiToParticipate); fundingRecipient.transfer(weiToParticipate); // Transfer tokens to recipient. uint256 tokensToTransfer = weiToParticipate.mul(CLN_PER_ETH); if (tokensLeftInSale.sub(tokensToTransfer) < CLN_PER_ETH) { // If purchase would cause less than CLN_PER_ETH tokens to be left then nobody could ever buy them. // So, gift them to the last buyer. tokensToTransfer = tokensLeftInSale; } tokensSold = tokensSold.add(tokensToTransfer); require(transferTokens(_recipient, tokensToTransfer)); // Partial refund if full participation not possible // e.g. due to cap being reached. uint256 refund = msg.value.sub(weiToParticipate); if (refund > 0) { msg.sender.transfer(refund); } } /// @dev Finalizes the token sale event: make future development pool grant (lockup) and make token transfarable. function finalize() external onlyAfterSale onlyOwner isInitialized { if (cln.isTransferable()) { revert(); } // Add unsold token to the future development pool grant (lockup). uint256 tokensLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold); uint256 futureDevelopmentPool = FUTURE_DEVELOPMENT_POOL.add(tokensLeftInSale); // Future Development Pool is locked for 3 years. grant(futureDevelopmentPoolAddress, futureDevelopmentPool, startTime, startTime.add(3 years), startTime.add(3 years), 1 days, false); // Make tokens Transferable, end the sale!. cln.makeTokensTransferable(); } function grant(address _grantee, uint256 _amount, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable) private { // bytes4 grantSig = bytes4(keccak256("grant(address,uint256,uint256,uint256,uint256,bool)")); bytes4 grantSig = 0x5ee7e96d; // 6 arguments of size 32 uint256 argsSize = 6 * 32; // sig + arguments size uint256 dataSize = 4 + argsSize; bytes memory m_data = new bytes(dataSize); assembly { // Add the signature first to memory mstore(add(m_data, 0x20), grantSig) // Add the parameters mstore(add(m_data, 0x24), _grantee) mstore(add(m_data, 0x44), _start) mstore(add(m_data, 0x64), _cliff) mstore(add(m_data, 0x84), _end) mstore(add(m_data, 0xa4), _installmentLength) mstore(add(m_data, 0xc4), _revokable) } require(transferTokens(trustee, _amount, m_data)); } /// @dev Transfer tokens from the sale contract to a recipient. /// @param _recipient address The address of the recipient. /// @param _tokens uint256 The amount of tokens to transfer. function transferTokens(address _recipient, uint256 _tokens) private returns (bool ans) { ans = cln.transfer(_recipient, _tokens); if (ans) { TokensIssued(_recipient, _tokens); } } /// @dev Transfer tokens from the sale contract to a recipient. /// @param _recipient address The address of the recipient. /// @param _tokens uint256 The amount of tokens to transfer. /// @param _data bytes data to send to receiver if it is a contract. function transferTokens(address _recipient, uint256 _tokens, bytes _data) private returns (bool ans) { // Request Colu Local Network contract to transfer the requested tokens for the buyer. ans = cln.transferAndCall(_recipient, _tokens, _data); if (ans) { TokensIssued(_recipient, _tokens); } } /// @dev Requests to transfer control of the Colu Local Network contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call Colu Local Network contract's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale to continue, since only the owner of /// the Colu Local Network contract can transfer tokens during the sale. function requestColuLocalNetworkOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { cln.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the Colu Local Network contract. // This can be used by the sale contract itself to claim back ownership of the Colu Local Network contract. function acceptColuLocalNetworkOwnership() external onlyOwner { cln.acceptOwnership(); } /// @dev Requests to transfer control of the VestingTrustee contract to a new owner. /// @param _newOwnerCandidate address The address to transfer ownership to. /// /// NOTE: /// 1. The new owner will need to call trustee contract's acceptOwnership directly in order to accept the ownership. /// 2. Calling this method during the token sale will prevent the token sale from alocation presale grunts add finalize, since only the owner of /// the trustee contract can create grunts needed in the presaleAlocation add finalize methods. function requestVestingTrusteeOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { trustee.requestOwnershipTransfer(_newOwnerCandidate); } /// @dev Accepts new ownership on behalf of the VestingTrustee contract. /// This can be used by the token sale contract itself to claim back ownership of the VestingTrustee contract. function acceptVestingTrusteeOwnership() external onlyOwner { trustee.acceptOwnership(); } }
Update total vesting amount and transfer previously calculated tokens to owner.
totalVesting = totalVesting.sub(refund);
1,083,119
[ 1, 1891, 2078, 331, 10100, 3844, 471, 7412, 7243, 8894, 2430, 358, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 58, 10100, 273, 2078, 58, 10100, 18, 1717, 12, 1734, 1074, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./IERC777.sol"; import "./IERC777Recipient.sol"; import "./IERC777Sender.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../IERC1820Registry.sol"; /** * @title ERC777 token implementation * @author etsvigun <[email protected]>, Bertrand Masius <[email protected]> */ contract ERC777 is IERC777 { using SafeMath for uint256; using Address for address; IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); string private _name; string private _symbol; mapping(address => uint256) private _balances; uint256 private _totalSupply; uint256 private _granularity; bytes32 constant private TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; constructor( string memory name, string memory symbol, uint256 granularity, address[] memory defaultOperators ) public { require(granularity > 0); _name = name; _symbol = symbol; _granularity = granularity; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interface _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); } /** * @dev Send the amount of tokens from the address msg.sender to the address to * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param data bytes information attached to the send, and intended for the recipient (to) */ function send(address to, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, to, amount, data, ""); } /** * @dev Send the amount of tokens on behalf of the address from to the address to * @param from address token holder address. * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param data bytes information attached to the send, and intended for the recipient (to) * @param operatorData bytes extra information provided by the operator (if any) */ function operatorSend( address from, address to, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, from)); _send(msg.sender, from, to, amount, data, operatorData); } /** * @dev Burn the amount of tokens from the address msg.sender * @param amount uint256 amount of tokens to transfer * @param data bytes extra information provided by the token holder */ function burn(uint256 amount, bytes calldata data) external { _burn(msg.sender, msg.sender, amount, data, ""); } /** * @dev Burn the amount of tokens on behalf of the address from * @param from address token holder address. * @param amount uint256 amount of tokens to transfer * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function operatorBurn(address from, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, from)); _burn(msg.sender, from, amount, data, operatorData); } /** * @dev Authorize an operator for the sender * @param operator address to be authorized as operator */ function authorizeOperator(address operator) external { require(msg.sender != operator); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev Revoke operator rights from one of the default operators * @param operator address to revoke operator rights from */ function revokeOperator(address operator) external { require(operator != msg.sender); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param tokenHolder The address to query the balance of. * @return uint256 representing the amount owned by the specified address. */ function balanceOf(address tokenHolder) public view returns (uint256) { return _balances[tokenHolder]; } /** * @dev Gets the token's granularity, * i.e. the smallest number of tokens (in the basic unit) * which may be minted, sent or burned at any time * @return uint256 granularity */ function granularity() public view returns (uint256) { return _granularity; } /** * @dev Get the list of default operators as defined by the token contract. * @return address[] default operators */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev Indicate whether an address * is an operator of the tokenHolder address * @param operator address which may be an operator of tokenHolder * @param tokenHolder address of a token holder which may have the operator * address as an operator. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev Mint tokens. Does not check authorization of operator * @dev the caller may ckeck that operator is authorized before calling * @param operator address operator requesting the operation * @param to address token recipient address * @param amount uint256 amount of tokens to mint * @param userData bytes extra information defined by the token recipient (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _mint( address operator, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { require(to != address(0)); require((amount % _granularity) == 0); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[to] = _balances[to].add(amount); _callTokensReceived(operator, address(0), to, amount, userData, operatorData); emit Minted(operator, to, amount, userData, operatorData); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0)); require(to != address(0)); require((amount % _granularity) == 0); _callTokensToSend(operator, from, to, amount, userData, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount); _balances[to] = _balances[to].add(amount); _callTokensReceived(operator, from, to, amount, userData, operatorData); emit Sent(operator, from, to, amount, userData, operatorData); } /** * @dev Burn tokens * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0)); require((amount % _granularity) == 0); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _totalSupply = _totalSupply.sub(amount); _balances[from] = _balances[from].sub(amount); emit Burned(operator, from, amount, data, operatorData); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else { require(!to.isContract()); } } }
* @dev Burn tokens @param operator address operator requesting the operation @param from address token holder address @param amount uint256 amount of tokens to burn @param data bytes extra information provided by the token holder @param operatorData bytes extra information provided by the operator (if any)/ Update state variables
function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0)); require((amount % _granularity) == 0); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _totalSupply = _totalSupply.sub(amount); _balances[from] = _balances[from].sub(amount); emit Burned(operator, from, amount, data, operatorData); }
13,057,314
[ 1, 38, 321, 2430, 225, 3726, 1758, 3726, 18709, 326, 1674, 225, 628, 1758, 1147, 10438, 1758, 225, 3844, 2254, 5034, 3844, 434, 2430, 358, 18305, 225, 501, 1731, 2870, 1779, 2112, 635, 326, 1147, 10438, 225, 3726, 751, 1731, 2870, 1779, 2112, 635, 326, 3726, 261, 430, 1281, 13176, 2315, 919, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 12, 203, 3639, 1758, 3726, 16, 203, 3639, 1758, 628, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 3778, 501, 16, 203, 3639, 1731, 3778, 3726, 751, 203, 565, 262, 203, 565, 3238, 203, 565, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12443, 8949, 738, 389, 75, 27234, 13, 422, 374, 1769, 203, 203, 3639, 389, 1991, 5157, 28878, 12, 9497, 16, 628, 16, 1758, 12, 20, 3631, 3844, 16, 501, 16, 3726, 751, 1769, 203, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 8949, 1769, 203, 3639, 389, 70, 26488, 63, 2080, 65, 273, 389, 70, 26488, 63, 2080, 8009, 1717, 12, 8949, 1769, 203, 203, 3639, 3626, 605, 321, 329, 12, 9497, 16, 628, 16, 3844, 16, 501, 16, 3726, 751, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract AccessAccount{ //the banks address address bankAddress; //the owners address address onwerAddress; //the balance of the account uint balance; //the accounts limit uint accountLimit; //if the account is frozen bool frozen; //the different types of acounts enum AccountType {access, delay, trust} //this accounts type AccountType thisAccountType; event LogCreatedAccessAcount(address _owner, address _bank, AccountType _accountType); /** * @dev checks that the msg.sender is an owner of the contract */ modifier isOwner() { require(msg.sender == bankAddress || msg.sender == onwerAddress, "Function only accessible by owner"); _; } /** * @dev checks that the bank is the only address able of using the function */ modifier isBank() { require(msg.sender == bankAddress, "Function only usable by bank"); _; } /** * @dev checks the account is not frozen, and that the account is not dissolved */ modifier isFrozen() { require(frozen == false, "Account is frozen"); _; } /** * @param _owner : the address of the user creating the account * @param _chosenType : the type of account this instance is (as this is the parent contract) * @dev creates a new access acount, logs creation */ constructor(address _owner, AccountType _chosenType, uint _limit) public { onwerAddress = _owner; bankAddress = msg.sender; thisAccountType = _chosenType; accountLimit = _limit; frozen = false; emit LogCreatedAccessAcount(_owner, msg.sender, _chosenType); } /** * @dev returns if the account is frozen (true) or (false) if not */ function getFrozen() public view returns(bool) { return frozen; } /** * @dev returns the type of account */ function getAccountType() public view returns(AccountType) { return thisAccountType; } /** * @dev allows for anyone to check the balance of an account */ function getBalance() public view returns(uint) { return balance; } /** * @dev returns the owner of access and delay accounts. */ function getOwner() public view isOwner() returns(address) { require(thisAccountType != AccountType.trust, "Please use getOwners() in trust contract"); return onwerAddress; } /** * @dev returns the limit of the account. The caller must be an owner */ function getLimit() public view isOwner() returns(uint) { return accountLimit; } /** * @param _newLimit : the new limit * @dev allows the bank to change the limit of an account. * @notice there are no checks here as the bank contains them. * The chekcs are to ensure that the limit is not less than * the current balance as to prevent errors of exceeding limits. */ function setLimit(uint _newLimit) public isBank() { accountLimit = _newLimit; } /** * @dev freezed the account. The isFrozen() is used to ensure an already * frozen account cannot be frozen again. */ function freeze() public isOwner() isFrozen() { frozen = true; } /** * @dev unfreezes account. Manually checks the account is not dissolved. */ function defrost() public isOwner() { require(frozen == true, "Account already unfrozen"); frozen = false; } event LogProgress(string _desc); /** * @dev lets the bank dissolve account, sending all funds to the owner */ function dissolve() public isBank() { frozen = true; emit LogProgress("(access) disolve"); selfdestruct(onwerAddress); } /** * @param _newOwnerAddress : the address of the new owner. * @dev allows the user to change the wallet assosiated with the account. * The require ensures that this function cannot be called on the trust account * from the parent function (this function). */ function changeOwner(address _newOwnerAddress) public isBank() isFrozen() { freeze(); require(thisAccountType != AccountType.trust, "Please use changeOwner function in trust contract"); onwerAddress = _newOwnerAddress; defrost(); } /** * @dev allows anyone to deposit into the account, as depositing can be * done by any wallet. Requires the amount to be greater than 0 and also * ensures that the balance will not overflow from deposit. */ function deposit() public payable isFrozen() { require(balance + msg.value > 0, "Value cannot make balance negative"); require(balance + msg.value <= accountLimit, "Deposit takes account over limit"); balance += msg.value; } /** * @param _amount : the amount to be withdrawn * @dev only allows the owner(s) to withdraw. Dose not allow use if account is frozen * (or dissolved). Ensures the usage of witdraw in the child contracts for both delay * contracts and trust contracts. */ function withdraw(uint _amount) public isOwner() isFrozen() { freeze(); require(thisAccountType == AccountType.access, "Please use withdraw function in child contract"); require(_amount <= balance, "Cannot withdraw more funds than available"); balance -= _amount; onwerAddress.transfer(_amount); defrost(); } /** * @dev fallback function adds value to balance */ function () public payable { balance+= msg.value; } }
* @dev checks that the bank is the only address able of using the function/
modifier isBank() { require(msg.sender == bankAddress, "Function only usable by bank"); _; }
5,528,288
[ 1, 12366, 716, 326, 11218, 353, 326, 1338, 1758, 7752, 434, 1450, 326, 445, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 353, 16040, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 11218, 1887, 16, 315, 2083, 1338, 15603, 635, 11218, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xc3f2C8F9d5F0705De706b1302B7a039e1e11aC88/sources/contracts/logic/RailgunLogic.sol
* @notice Transfers tokens to contract and adjusts preimage with fee values @param _note - note to process/ validateTransaction and accumulateAndNullifyTransaction functions MUST be called in that order BEFORE invoking this function to process an unshield on a transaction else reentrancy attacks are possible Process unshield request ERC20 Get ERC20 interface Get base and fee amounts Transfer base to output address Transfer fee to treasury Emit unshield event ERC721 token Get ERC721 interface Transfer NFT to output address Emit unshield event ERC1155 token
function transferTokenOut(CommitmentPreimage calldata _note) internal { if (_note.token.tokenType == TokenType.ERC20) { IERC20 token = IERC20(address(uint160(_note.token.tokenAddress))); (uint120 base, uint120 fee) = getFee(_note.value, true, unshieldFee); token.safeTransfer(address(uint160(uint256(_note.npk))), base); token.safeTransfer(treasury, fee); emit Unshield(address(uint160(uint256(_note.npk))), _note.token, base, fee); IERC721 token = IERC721(address(uint160(_note.token.tokenAddress))); token.transferFrom( address(this), address(uint160(uint256(_note.npk))), _note.token.tokenSubID ); emit Unshield(address(uint160(uint256(_note.npk))), _note.token, 1, 0); revert("RailgunLogic: ERC1155 not yet supported"); } }
17,076,235
[ 1, 1429, 18881, 2430, 358, 6835, 471, 5765, 87, 675, 2730, 598, 14036, 924, 225, 389, 7652, 300, 4721, 358, 1207, 19, 1954, 3342, 471, 21757, 1876, 2041, 1164, 3342, 4186, 10685, 506, 2566, 316, 716, 1353, 21203, 15387, 333, 445, 358, 1207, 392, 640, 674, 491, 603, 279, 2492, 469, 283, 8230, 12514, 28444, 854, 3323, 4389, 640, 674, 491, 590, 4232, 39, 3462, 968, 4232, 39, 3462, 1560, 968, 1026, 471, 14036, 30980, 12279, 1026, 358, 876, 1758, 12279, 14036, 358, 9787, 345, 22498, 16008, 640, 674, 491, 871, 4232, 39, 27, 5340, 1147, 968, 4232, 39, 27, 5340, 1560, 12279, 423, 4464, 358, 876, 1758, 16008, 640, 674, 491, 871, 4232, 39, 2499, 2539, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1345, 1182, 12, 5580, 475, 1386, 2730, 745, 892, 389, 7652, 13, 2713, 288, 203, 203, 565, 309, 261, 67, 7652, 18, 2316, 18, 2316, 559, 422, 18794, 18, 654, 39, 3462, 13, 288, 203, 203, 1377, 467, 654, 39, 3462, 1147, 273, 467, 654, 39, 3462, 12, 2867, 12, 11890, 16874, 24899, 7652, 18, 2316, 18, 2316, 1887, 3719, 1769, 203, 203, 1377, 261, 11890, 22343, 1026, 16, 2254, 22343, 14036, 13, 273, 2812, 1340, 24899, 7652, 18, 1132, 16, 638, 16, 640, 674, 491, 14667, 1769, 203, 203, 1377, 1147, 18, 4626, 5912, 12, 2867, 12, 11890, 16874, 12, 11890, 5034, 24899, 7652, 18, 82, 5465, 3719, 3631, 1026, 1769, 203, 203, 1377, 1147, 18, 4626, 5912, 12, 27427, 345, 22498, 16, 14036, 1769, 203, 203, 1377, 3626, 1351, 674, 491, 12, 2867, 12, 11890, 16874, 12, 11890, 5034, 24899, 7652, 18, 82, 5465, 3719, 3631, 389, 7652, 18, 2316, 16, 1026, 16, 14036, 1769, 203, 203, 1377, 467, 654, 39, 27, 5340, 1147, 273, 467, 654, 39, 27, 5340, 12, 2867, 12, 11890, 16874, 24899, 7652, 18, 2316, 18, 2316, 1887, 3719, 1769, 203, 203, 1377, 1147, 18, 13866, 1265, 12, 203, 3639, 1758, 12, 2211, 3631, 203, 3639, 1758, 12, 11890, 16874, 12, 11890, 5034, 24899, 7652, 18, 82, 5465, 3719, 3631, 203, 3639, 389, 7652, 18, 2316, 18, 2316, 1676, 734, 203, 1377, 11272, 203, 203, 1377, 3626, 1351, 674, 491, 12, 2867, 12, 11890, 16874, 12, 11890, 5034, 24899, 7652, 18, 82, 5465, 3719, 3631, 2 ]
./full_match/1/0xC5f19ABaF35866A1063e53204b60981C2635Bb39/sources/browser/zereus.sol
@dev The tax fee contains two decimal places, so 100 = 1%
contract ZEREUS is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; string private _name = "Zereus Protocol"; string private _symbol = "ZER"; uint8 private _decimals = 9; mapping(address => uint256) internal _reflectionBalance; mapping(address => uint256) internal _tokenBalance; mapping(address => mapping(address => uint256)) internal _allowances; uint256 private constant MAX = ~uint256(0); uint256 internal _tokenTotal = 50_000e9; uint256 internal _reflectionTotal = (MAX - (MAX % _tokenTotal)); mapping(address => bool) isExcludedFromFee; mapping(address => bool) internal _isExcluded; address[] internal _excluded; uint256 public _feeDecimal = 2; uint256 public _taxFee = 200; uint256 public _liquidityFee = 200; uint256 public _rebalanceCallerFee = 500; uint256 public _taxFeeTotal; uint256 public _burnFeeTotal; uint256 public _liquidityFeeTotal; bool public tradingEnabled = false; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public rebalanceEnalbed = true; uint256 public minTokensBeforeSwap = 100; uint256 public minEthBeforeSwap = 100; uint256 public liquidityAddedAt; uint256 public lastTaxIncreasedTime; uint256 public lastRebalance = now ; uint256 public rebalanceInterval = 30 minutes; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public balancer; event TradingEnabled(bool enabled); event RewardsDistributed(uint256 amount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapedTokenForEth(uint256 EthAmount, uint256 TokenAmount); event SwapedEthForTokens(uint256 EthAmount, uint256 TokenAmount, uint256 CallerReward, uint256 AmountBurned); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() public { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; balancer = address(new Balancer()); isExcludedFromFee[_msgSender()] = true; isExcludedFromFee[address(this)] = true; _isExcluded[uniswapV2Pair] = true; _excluded.push(uniswapV2Pair); _reflectionBalance[_msgSender()] = _reflectionTotal; emit Transfer(address(0), _msgSender(), _tokenTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public override view returns (uint256) { return _tokenTotal; } function balanceOf(address account) public override view returns (uint256) { if (_isExcluded[account]) return _tokenBalance[account]; return tokenFromReflection(_reflectionBalance[account]); } function transfer(address recipient, uint256 amount) public override virtual returns (bool) { _transfer(_msgSender(),recipient,amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override virtual returns (bool) { _transfer(sender,recipient,amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub( amount,"ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(),spender,_allowances[_msgSender()][spender].sub(subtractedValue,"ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee) public view returns (uint256) { require(tokenAmount <= _tokenTotal, "Amount must be less than supply"); if (!deductTransferFee) { return tokenAmount.mul(_getReflectionRate()); return tokenAmount.sub(tokenAmount.mul(_taxFee).div(10** _feeDecimal + 2)).mul(_getReflectionRate()); } } function reflectionFromToken(uint256 tokenAmount, bool deductTransferFee) public view returns (uint256) { require(tokenAmount <= _tokenTotal, "Amount must be less than supply"); if (!deductTransferFee) { return tokenAmount.mul(_getReflectionRate()); return tokenAmount.sub(tokenAmount.mul(_taxFee).div(10** _feeDecimal + 2)).mul(_getReflectionRate()); } } } else { function tokenFromReflection(uint256 reflectionAmount) public view returns (uint256) { require( reflectionAmount <= _reflectionTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getReflectionRate(); return reflectionAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require( account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, "AERUS: Uniswap router cannot be excluded." ); require(account != address(this), 'AERUS: The contract it self cannot be excluded'); require(!_isExcluded[account], "AERUS: Account is already excluded"); if (_reflectionBalance[account] > 0) {_tokenBalance[account] = tokenFromReflection(_reflectionBalance[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeAccount(address account) external onlyOwner() { require( account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, "AERUS: Uniswap router cannot be excluded." ); require(account != address(this), 'AERUS: The contract it self cannot be excluded'); require(!_isExcluded[account], "AERUS: Account is already excluded"); if (_reflectionBalance[account] > 0) {_tokenBalance[account] = tokenFromReflection(_reflectionBalance[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "AERUS: Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tokenBalance[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "AERUS: Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tokenBalance[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "AERUS: Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tokenBalance[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } _reflectionBalance[sender] = _reflectionBalance[sender].sub(amount.mul(rate)); function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(tradingEnabled || sender == owner() || recipient == owner() || isExcludedFromFee[sender] || isExcludedFromFee[recipient], "Trading is locked before presale."); require(now > liquidityAddedAt + 7 minutes || amount <= 1200e9, "You cannot transfer more than 1200 tokens."); if(lastTaxIncreasedTime != 0 && now > lastTaxIncreasedTime + 6 hours && _taxFee < 4 && _liquidityFee < 4){ _taxFee += 100; _liquidityFee += 100; lastTaxIncreasedTime = now; } if(!inSwapAndLiquify && sender != uniswapV2Pair) { bool swap = true; uint256 contractBalance = address(this).balance; if(now > lastRebalance + rebalanceInterval && rebalanceEnalbed && contractBalance >= minEthBeforeSwap){ buyAndBurnToken(contractBalance); swap = false; } if(swap) { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if (overMinTokenBalance && swapAndLiquifyEnabled) { swapTokensForEth(); } } } uint256 transferAmount = amount; uint256 rate = _getReflectionRate(); if(!isExcludedFromFee[sender] && !isExcludedFromFee[recipient] && !inSwapAndLiquify){ transferAmount = collectFee(sender,amount,rate); } _reflectionBalance[recipient] = _reflectionBalance[recipient].add(transferAmount.mul(rate)); if (_isExcluded[sender]) { _tokenBalance[sender] = _tokenBalance[sender].sub(amount); } if (_isExcluded[recipient]) { _tokenBalance[recipient] = _tokenBalance[recipient].add(transferAmount); } emit Transfer(sender, recipient, transferAmount); } function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; if(_taxFee != 0){ uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); emit RewardsDistributed(taxFee); } if(_liquidityFee != 0){ uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(liquidityFee); _reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate)); _liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee); emit Transfer(account,address(this),liquidityFee); } return transferAmount; } function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; if(_taxFee != 0){ uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); emit RewardsDistributed(taxFee); } if(_liquidityFee != 0){ uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(liquidityFee); _reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate)); _liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee); emit Transfer(account,address(this),liquidityFee); } return transferAmount; } function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; if(_taxFee != 0){ uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); emit RewardsDistributed(taxFee); } if(_liquidityFee != 0){ uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(liquidityFee); _reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate)); _liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee); emit Transfer(account,address(this),liquidityFee); } return transferAmount; } function _getReflectionRate() private view returns (uint256) { uint256 reflectionSupply = _reflectionTotal; uint256 tokenSupply = _tokenTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _reflectionBalance[_excluded[i]] > reflectionSupply || _tokenBalance[_excluded[i]] > tokenSupply ) return _reflectionTotal.div(_tokenTotal); reflectionSupply = reflectionSupply.sub( _reflectionBalance[_excluded[i]] ); tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]); } if (reflectionSupply < _reflectionTotal.div(_tokenTotal)) return _reflectionTotal.div(_tokenTotal); return reflectionSupply.div(tokenSupply); } function _getReflectionRate() private view returns (uint256) { uint256 reflectionSupply = _reflectionTotal; uint256 tokenSupply = _tokenTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _reflectionBalance[_excluded[i]] > reflectionSupply || _tokenBalance[_excluded[i]] > tokenSupply ) return _reflectionTotal.div(_tokenTotal); reflectionSupply = reflectionSupply.sub( _reflectionBalance[_excluded[i]] ); tokenSupply = tokenSupply.sub(_tokenBalance[_excluded[i]]); } if (reflectionSupply < _reflectionTotal.div(_tokenTotal)) return _reflectionTotal.div(_tokenTotal); return reflectionSupply.div(tokenSupply); } function swapTokensForEth() private lockTheSwap { uint256 tokenAmount = balanceOf(address(this)); uint256 ethAmount = address(this).balance; address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); ethAmount = address(this).balance.sub(ethAmount); emit SwapedTokenForEth(tokenAmount,ethAmount); } function swapEthForTokens(uint256 EthAmount) private { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); 0, path, address(balancer), block.timestamp ); } uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: EthAmount}( function buyAndBurnToken(uint256 contractBalance) private lockTheSwap { lastRebalance = now; swapEthForTokens(contractBalance); uint256 swapedTokens = balanceOf(address(balancer)); uint256 rewardForCaller = swapedTokens.mul(_rebalanceCallerFee).div(10**(_feeDecimal + 2)); uint256 amountToBurn = swapedTokens.sub(rewardForCaller); uint256 rate = _getReflectionRate(); _reflectionBalance[tx.origin] = _reflectionBalance[tx.origin].add(rewardForCaller.mul(rate)); _reflectionBalance[address(balancer)] = 0; _burnFeeTotal = _burnFeeTotal.add(amountToBurn); _tokenTotal = _tokenTotal.sub(amountToBurn); _reflectionTotal = _reflectionTotal.sub(amountToBurn.mul(rate)); emit Transfer(address(balancer), tx.origin, rewardForCaller); emit Transfer(address(balancer), address(0), amountToBurn); emit SwapedEthForTokens(contractBalance, swapedTokens, rewardForCaller, amountToBurn); } function setExcludedFromFee(address account, bool excluded) public onlyOwner { isExcludedFromFee[account] = excluded; } function setSwapAndLiquifyEnabled(bool enabled) public onlyOwner { swapAndLiquifyEnabled = enabled; SwapAndLiquifyEnabledUpdated(enabled); } function setTaxFee(uint256 fee) public onlyOwner { _taxFee = fee; } function setLiquidityFee(uint256 fee) public onlyOwner { _liquidityFee = fee; } function setRebalanceCallerFee(uint256 fee) public onlyOwner { _rebalanceCallerFee = fee; } function setMinTokensBeforeSwap(uint256 amount) public onlyOwner { minTokensBeforeSwap = amount; } function setMinEthBeforeSwap(uint256 amount) public onlyOwner { minEthBeforeSwap = amount; } function setRebalanceInterval(uint256 interval) public onlyOwner { rebalanceInterval = interval; } function setRebalanceEnabled(bool enabled) public onlyOwner { rebalanceEnalbed = enabled; } function enableTrading() external onlyOwner() { tradingEnabled = true; TradingEnabled(true); liquidityAddedAt = now; lastTaxIncreasedTime = now; } receive() external payable {} }
2,985,477
[ 1, 1986, 5320, 14036, 1914, 2795, 6970, 12576, 16, 1427, 2130, 273, 404, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2285, 29340, 3378, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 533, 3238, 389, 529, 273, 315, 62, 822, 407, 4547, 14432, 203, 565, 533, 3238, 389, 7175, 273, 315, 62, 654, 14432, 203, 565, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 389, 26606, 13937, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 389, 2316, 13937, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 2713, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 2713, 389, 2316, 5269, 273, 6437, 67, 3784, 73, 29, 31, 203, 565, 2254, 5034, 2713, 389, 26606, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 2316, 5269, 10019, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 353, 16461, 1265, 14667, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 2713, 389, 291, 16461, 31, 203, 565, 1758, 8526, 2713, 389, 24602, 31, 203, 377, 203, 565, 2254, 5034, 1071, 389, 21386, 5749, 273, 576, 31, 203, 565, 2254, 5034, 1071, 389, 8066, 14667, 273, 4044, 31, 203, 565, 2254, 5034, 1071, 389, 549, 372, 24237, 14667, 273, 4044, 31, 203, 203, 565, 2254, 5034, 1071, 389, 266, 12296, 11095, 14667, 273, 6604, 31, 203, 203, 565, 2254, 5034, 1071, 2 ]
pragma solidity ^0.4.24; import "../../open-zeppelin/contracts/math/SafeMath.sol"; import "./Closable.sol"; import "./ChainOwner.sol"; import "./ICO.sol"; /** * @title Sale smart contract * @author Biglabs Pte. Ltd. * @dev : ICO Sale based smart contract */ contract Sale is ChainOwner, Closable { using SafeMath for uint; //Sale Token ref ICO internal smzoToken; //Sold tokens uint internal sold; /** * @dev Sale constructor * @param _ico ICO smart contract */ constructor(ICO _ico) internal ChainOwner(_ico) onlyOwner() { smzoToken = _ico; } /** * @dev Fall back function ~ buyToken */ function() public payable { require(msg.data.length == 0); buyToken(); } /** * @dev Get ICO smart contract */ function ico() public view returns (ICO) { return smzoToken; } /** * @dev Get the number of remain tokens */ function noTokens() public view returns (uint) { return smzoToken.balanceOf(this); } /** * @dev Investor buy Sale Token use ETH */ function buyToken() public payable returns (bool) { uint tokenToFund = _calculateToken(); _checkNoToken(tokenToFund); //collect eth _collectMoney(); bool ret = smzoToken.transferByEth(msg.sender, msg.value, tokenToFund); if (ret) { sold = sold.add(tokenToFund); } return ret; } /** * @dev Get number of sold tokens */ function getSoldToken() public view returns (uint) { return sold; } /** * @dev Owner withdraw all accidentally Eth * */ function withdraw() public onlyOwner { _widthdraw(); } /** * @dev Owner get all unsold tokens back * */ function returnToken() public onlyOwner notClosed { _returnToken(noTokens().sub(_holdTokens())); } /** * @dev Check whether tokens is enough for buying */ function _checkNoToken(uint _value) internal view { require(_value <= noTokens()); } /** * @dev Calculate number of tokens based on wei contribution */ function _calculateToken() internal view returns (uint) { return ico().calculateNoToken(msg.value); } /** * @dev Collect money (send eth to owner wallet) */ function _collectMoney() internal { return owner().transfer(msg.value); } function _widthdraw() internal { //transfer accidentally eth in this contract if any to owner wallet if (address(this).balance > 0) { owner().transfer(address(this).balance); } } function _returnToken(uint no) internal { require(no > 0); ico().transfer(owner(), no); } /** * @dev Calculate number of tokens to be held */ function _holdTokens() internal view returns(uint) { return 0; } function _bonusProcess() internal { //default //Noop } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner requireClosed public { selfdestruct(owner()); } /** * @dev Release the contract */ function _release() internal { _widthdraw(); _bonusProcess(); _returnToken(noTokens()); _close(); } }
* @dev Transfers the current balance to the owner and terminates the contract./
function destroy() onlyOwner requireClosed public { selfdestruct(owner()); }
7,274,113
[ 1, 1429, 18881, 326, 783, 11013, 358, 326, 3410, 471, 30559, 326, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5546, 1435, 1338, 5541, 2583, 7395, 1071, 288, 203, 3639, 365, 5489, 8813, 12, 8443, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4852a488F15AE544C75FED466908A2D1559EBAfa/sources/contracts/DrainController.sol
* @notice Change the maximum gas price in Gwei for refunds/
function setMaxGasPrice(uint256 maxGasPrice_) external onlyOwner { maxGasPrice = maxGasPrice_; }
4,399,541
[ 1, 3043, 326, 4207, 16189, 6205, 316, 611, 1814, 77, 364, 16255, 87, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10851, 27998, 5147, 12, 11890, 5034, 943, 27998, 5147, 67, 13, 3903, 1338, 5541, 288, 203, 3639, 943, 27998, 5147, 273, 943, 27998, 5147, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Arrays.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "./allowlist/AllowList.sol"; import "./traits/TokenTraits.sol"; import "./traits/ITraits.sol"; import "./IVampireGame.sol"; /// @title The Vampire Game NFT contract /// /// Note: The original Wolf Game's contract was used as insipiration, and a /// few parts of the contract were taken directly, in particular the trait selection /// and rarity using Walker's Alias method, and using a separate `Traits` contract /// for getting the tokenURI. /// /// Some info about how this contract works: /// /// ### Allow-list /// /// Using a merkle-tree based allow-list that caps the amount of nfts a wallet /// can mint. This increases a bit the gas cost to mint on **presale**, but we /// compensate this by paying half of the minting price when we reveal the NFTs. /// /// ### On-chain vs Off-chain /// /// What is on-chain here? /// - The generated traits /// - The revealed traits metadata /// - The traits img data /// /// What is off-chain? /// - The random number we get for batch reveals. We use a neutral, trusted third party /// that is widely known in the community: Chainlink VRF. /// - The non-revealed traits metadata (before your nft is revealed). /// /// ### Minting and Revealing /// /// 1. The user mints an NFT /// 2. After a few mints, we request a random number to Chainlink VRF /// 3. We use this random number to reveal the batch of NFTs that were minted /// before we got the seed. /// /// Why? We believe that as long as minting and revealing happens in the same /// transaction, people will be able to cheat. /// /// ### Traits /// /// The traits are all stored on-chain in another contract "Traits" similar to Wolf Game. /// /// ### Game Controllers /// /// For us to be able to expand on this game, future "game controller" contracts will be /// able to freely call `mint` functions, and `transferFrom`, the logic to safeguard /// those functions will be delegated to those contracts. /// /// Unfortunatelly, to be able to expand, and to not fall into traps like Wolf Game did, /// we had to leave a few things open that requires our users to _trust us_ for now. We /// hope to make this trustless some day. /// contract VampireGame is IVampireGame, IVampireGameControls, ERC721Enumerable, AllowList, Ownable, ReentrancyGuard, VRFConsumerBase { /// @notice used to find seeds for token ids using Arrays for uint256[]; /// ==== Immutable // Most of the immutable variables are initiated in the constructor // to make it easier to test /// @notice minting price in wei uint256 public immutable MINT_PRICE; /// @notice max amount of tokens that can be minted uint256 public immutable MAX_SUPPLY; /// @notice max mints per address uint256 public immutable MAX_PER_ADDRESS; /// @notice max mints per address in presale uint256 public immutable MAX_PER_ADDRESS_PRESALE; /// @notice price in $LINK to make VRF requests uint256 public LINK_VRF_PRICE; /// @notice number of tokens that can be bought with ether uint256 public PAID_TOKENS; /// @notice size of the batch that will be revealed by a single uint256 public SEED_BATCH_SIZE; /// @notice random numbers generated from Chainlink VRF. uint256[] public seeds; /// @notice array of tokenIds in ascending order that matches the length of the `seeds` array. /// @dev using this to set which seeds are for which token, for example if let's say /// the array has the values [100, 1000], then tokens from 0~99 will use seed[0] and /// tokens from 100~999 will use seed[1]. uint256[] public seedTokenBoundaries; /// @notice mapping from tokenId to tokenTraits mapping(uint256 => TokenTraits) public tokenTraits; /// @notice mapping from token hash to tokenId to prevent duplicated traits mapping(uint256 => uint256) public existingCombinations; /// @notice mapping from address to amount of tokens minted mapping(address => uint8) public amountMintedByAddress; /// @notice game controllers they can access special functions mapping(address => bool) public controllers; /// @notice chainlink key hash bytes32 public immutable KEY_HASH; /// @notice LINK token IERC20 public immutable LINK_TOKEN; /// @notice contract storing the traits data ITraits public traits; /// @notice address to withdraw the eth address private immutable splitter; /// @notice controls if mintWithEthPresale is paused bool public mintWithEthPresalePaused = true; /// @notice controls if mintWithEth is paused bool public mintWithEthPaused = true; /// @notice controls if mintFromController is paused bool public mintFromControllerPaused = true; /// @notice controls if token reveal is paused bool public revealPaused = true; /// @notice list of probabilities for each trait type 0 - 9 are associated with Sheep, 10 - 18 are associated with Wolves /// @dev won't mutate but can't make it immutable uint8[][18] public RARITIES; /// @notice list of aliases for Walker's Alias algorithm 0 - 9 are associated with Sheep, 10 - 18 are associated with Wolves /// @dev won't mutate but can't make it immutable uint8[][18] public ALIASES; /// === Constructor /// @dev constructor, most of the immutable props can be set here so it's easier to test /// @param _LINK_KEY_HASH Chainlink's VRF Key Hash /// @param _LINK_ADDRESS Chainlink's LINK contract address /// @param _LINK_VRF_COORDINATOR_ADDRESS Chainlink's coordinator contract address /// @param _LINK_VRF_PRICE Price in $LINK to request a random number from Chainlink VRF /// @param _MINT_PRICE price to mint one token in wei /// @param _MAX_SUPPLY maximum amount of available tokens to mint /// @param _MAX_PER_ADDRESS maximum amount of tokens one address can mint /// @param _MAX_PER_ADDRESS_PRESALE maximum amount of tokens one address can mint /// @param _SEED_BATCH_SIZE amount of tokens revealed by one seed /// @param _PAID_TOKENS maxiumum amount of tokens that can be bought with eth /// @param _splitter address to where the funds will go constructor( bytes32 _LINK_KEY_HASH, address _LINK_ADDRESS, address _LINK_VRF_COORDINATOR_ADDRESS, uint256 _LINK_VRF_PRICE, uint256 _MINT_PRICE, uint256 _MAX_SUPPLY, uint256 _MAX_PER_ADDRESS, uint256 _MAX_PER_ADDRESS_PRESALE, uint256 _SEED_BATCH_SIZE, uint256 _PAID_TOKENS, address _splitter ) VRFConsumerBase(_LINK_VRF_COORDINATOR_ADDRESS, _LINK_ADDRESS) ERC721("The Vampire Game", "VGAME") { LINK_TOKEN = IERC20(_LINK_ADDRESS); KEY_HASH = _LINK_KEY_HASH; LINK_VRF_PRICE = _LINK_VRF_PRICE; MINT_PRICE = _MINT_PRICE; MAX_SUPPLY = _MAX_SUPPLY; MAX_PER_ADDRESS = _MAX_PER_ADDRESS; MAX_PER_ADDRESS_PRESALE = _MAX_PER_ADDRESS_PRESALE; SEED_BATCH_SIZE = _SEED_BATCH_SIZE; PAID_TOKENS = _PAID_TOKENS; splitter = _splitter; // Humans // Skin RARITIES[0] = [50, 15, 15, 250, 255]; ALIASES[0] = [3, 4, 4, 0, 3]; // Face RARITIES[1] = [ 133, 189, 57, 255, 243, 133, 114, 135, 168, 38, 222, 57, 95, 57, 152, 114, 57, 133, 189 ]; ALIASES[1] = [ 1, 0, 3, 1, 3, 3, 3, 4, 7, 4, 8, 4, 8, 10, 10, 10, 18, 18, 14 ]; // T-Shirt RARITIES[2] = [ 181, 224, 147, 236, 220, 168, 160, 84, 173, 224, 221, 254, 140, 252, 224, 250, 100, 207, 84, 252, 196, 140, 228, 140, 255, 183, 241, 140 ]; ALIASES[2] = [ 1, 0, 3, 1, 3, 3, 4, 11, 11, 4, 9, 10, 13, 11, 13, 14, 15, 15, 20, 17, 19, 24, 20, 24, 22, 26, 24, 26 ]; // Pants RARITIES[3] = [ 126, 171, 225, 240, 227, 112, 255, 240, 217, 80, 64, 160, 228, 80, 64, 167 ]; ALIASES[3] = [2, 0, 1, 2, 3, 3, 4, 6, 7, 4, 6, 7, 8, 8, 15, 12]; // Boots RARITIES[4] = [150, 30, 60, 255, 150, 60]; ALIASES[4] = [0, 3, 3, 0, 3, 4]; // Accessory RARITIES[5] = [ 210, 135, 80, 245, 235, 110, 80, 100, 190, 100, 255, 160, 215, 80, 100, 185, 250, 240, 240, 100 ]; ALIASES[5] = [ 0, 0, 3, 0, 3, 4, 10, 12, 4, 16, 8, 16, 10, 17, 18, 12, 15, 16, 17, 18 ]; // Hair RARITIES[6] = [250, 115, 100, 40, 175, 255, 180, 100, 175, 185]; ALIASES[6] = [0, 0, 4, 6, 0, 4, 5, 9, 6, 8]; // Cape RARITIES[7] = [255]; ALIASES[7] = [0]; // predatorIndex RARITIES[8] = [255]; ALIASES[8] = [0]; // Vampires // Skin RARITIES[9] = [ 234, 239, 234, 234, 255, 234, 244, 249, 130, 234, 234, 247, 234 ]; ALIASES[9] = [0, 0, 1, 2, 3, 4, 5, 6, 12, 7, 9, 10, 11]; // Face RARITIES[10] = [ 45, 255, 165, 60, 195, 195, 45, 120, 75, 75, 105, 120, 255, 180, 150 ]; ALIASES[10] = [1, 0, 1, 4, 2, 4, 5, 12, 12, 13, 13, 14, 5, 12, 13]; // Clothes RARITIES[11] = [ 147, 180, 246, 201, 210, 252, 219, 189, 195, 156, 177, 171, 165, 225, 135, 135, 186, 135, 150, 243, 135, 255, 231, 141, 183, 150, 135 ]; ALIASES[11] = [ 2, 2, 0, 2, 3, 4, 5, 6, 7, 3, 3, 4, 4, 8, 5, 6, 13, 13, 19, 16, 19, 19, 21, 21, 21, 21, 22 ]; // Pants RARITIES[12] = [255]; ALIASES[12] = [0]; // Boots RARITIES[13] = [255]; ALIASES[13] = [0]; // Accessory RARITIES[14] = [255]; ALIASES[14] = [0]; // Hair RARITIES[15] = [255]; ALIASES[15] = [0]; // Cape RARITIES[16] = [9, 9, 150, 90, 9, 210, 9, 9, 255]; ALIASES[16] = [5, 5, 0, 2, 8, 3, 8, 8, 5]; // predatorIndex RARITIES[17] = [255, 8, 160, 73]; ALIASES[17] = [0, 0, 0, 2]; } /// ==== Modifiers modifier onlyControllers() { require(controllers[_msgSender()], "ONLY_CONTROLLERS"); _; } /// ==== Minting /// @notice mint an unrevealed token using eth /// @param amount amount to mint function mintWithETH(uint8 amount) external payable nonReentrant { require(!mintWithEthPaused, "MINT_WITH_ETH_PAUSED"); uint8 addressMintedSoFar = amountMintedByAddress[_msgSender()]; require( addressMintedSoFar + amount <= MAX_PER_ADDRESS, "MAX_TOKEN_PER_WALLET" ); require(totalSupply() + amount <= PAID_TOKENS, "NOT_ENOUGH_TOKENS"); require(amount > 0, "INVALID_AMOUNT"); require(amount * MINT_PRICE == msg.value, "WRONG_VALUE"); amountMintedByAddress[_msgSender()] = addressMintedSoFar + amount; _mintMany(_msgSender(), amount); } /// @notice mint an unrevealed token using eth /// @param amount amount to mint function mintWithETHPresale(uint8 amount, bytes32[] calldata proof) external payable nonReentrant { require(!mintWithEthPresalePaused, "PRESALE_PAUSED"); require(isAddressInAllowList(_msgSender(), proof), "NOT_IN_ALLOWLIST"); uint8 addressMintedSoFar = amountMintedByAddress[_msgSender()]; require( addressMintedSoFar + amount <= MAX_PER_ADDRESS_PRESALE, "MAX_TOKEN_PER_WALLET" ); require(totalSupply() + amount <= PAID_TOKENS, "NOT_ENOUGH_TOKENS"); require(amount > 0, "INVALID_AMOUNT"); require(amount * MINT_PRICE == msg.value, "WRONG_VALUE"); amountMintedByAddress[_msgSender()] = addressMintedSoFar + amount; _mintMany(_msgSender(), amount); } /// @dev mint any amount of tokens to an address /// common logic to many functions, the function calling /// this should do the guard checks function _mintMany(address to, uint8 amount) private { uint256 supply = totalSupply(); for (uint8 i = 0; i < amount; i++) { uint256 tokenId = supply + i; _safeMint(to, tokenId); if ((tokenId + 1) % SEED_BATCH_SIZE == 0) { requestRandomness(KEY_HASH, LINK_VRF_PRICE); } } } /// ==== Revealing /// @notice reveal the metadata of multiple of tokenIds. /// @dev admin check if this won't fail function revealGenZeroTokens(uint256[] calldata tokenIds) external onlyOwner { for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(canRevealToken(tokenId), "CANT_REVEAL"); // Find seed index in the seedTokenBoundaries array uint256 seedIndex = seedTokenBoundaries.findUpperBound(tokenId); uint256 seed = uint256(keccak256(abi.encode(seeds[seedIndex], tokenId))); _revealToken(tokenId, seed); } } /// @dev returns true if a token can be revealed. /// Conditions for a token to be revealed: /// - Was not revealed yet /// - There is a seed that was added after the was already minted function canRevealToken(uint256 tokenId) private view returns (bool) { // Token already revealed if (tokenTraits[tokenId].exists) { return false; } // No seeds if (seedTokenBoundaries.length == 0) { return false; } // If the last element of the seedTokenBoundaries array is greater // than the tokenId it means that there is a seed available for that // token so the token can be revealed return seedTokenBoundaries[seedTokenBoundaries.length - 1] > tokenId; } /// @dev reveal one token given an id and a seed function _revealToken(uint256 tokenId, uint256 seed) private { ( TokenTraits memory tt, uint256 ttHash ) = _generateNonDuplicatedTokenTraits(tokenId, seed); tokenTraits[tokenId] = tt; existingCombinations[ttHash] = tokenId; } /// @dev recursive function to generate a TokenTraits without colliding /// with other previously generated traits. It uses a seed from /// Chainlink VRF and if there is a collision, it keeps re-hashing the /// seed with the tokenId until it finds a unique set of traits. /// @param tokenId the id of the token to generate the traits for /// @param seed a value derived from a randomly generated value /// @return tt a TokenTraits struct function _generateNonDuplicatedTokenTraits(uint256 tokenId, uint256 seed) private returns (TokenTraits memory tt, uint256 ttHash) { // generate traits from seed tt = selectTraits(seed); // hash to check if the token is unique ttHash = structToHash(tt); if (existingCombinations[ttHash] == 0) { tokenTraits[tokenId] = tt; existingCombinations[ttHash] = tokenId; return (tt, ttHash); } // If it's here, then the generated traits collided with another // set of traits. Hopefully this won't happen. // generates a new seed combining the current seed and the tokenId uint256 newSeed = uint256(keccak256(abi.encode(seed, tokenId))); // recursive call D: return _generateNonDuplicatedTokenTraits(tokenId, newSeed); } /// @dev select traits based on the seed value. /// @param seed a uint256 to derive traits from /// @return tt the TokenTraits function selectTraits(uint256 seed) private view returns (TokenTraits memory tt) { tt.exists = true; tt.isVampire = (seed & 0xFFFF) % 10 == 0; uint8 shift = tt.isVampire ? 9 : 0; seed >>= 16; tt.skin = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; tt.face = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; tt.clothes = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; tt.pants = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; tt.boots = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; tt.accessory = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; tt.hair = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; tt.cape = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; tt.predatorIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); } /// @dev select a trait from the traitType /// @param seed a uint256 number to get the trait value from /// @param traitType the trait type function selectTrait(uint16 seed, uint8 traitType) private view returns (uint8) { uint8 trait = uint8(seed) % uint8(RARITIES[traitType].length); if (seed >> 8 < RARITIES[traitType][trait]) return trait; return ALIASES[traitType][trait]; } /// @dev hash a TokenTraits struct /// @param tt the TokenTraits struct /// @return the uint256 hash function structToHash(TokenTraits memory tt) private pure returns (uint256) { return uint256( bytes32( abi.encodePacked( tt.isVampire, tt.skin, tt.face, tt.clothes, tt.pants, tt.boots, tt.accessory, tt.hair, tt.cape, tt.predatorIndex ) ) ); } /// ==== State Control /// @notice set the new merkle tree root for allow-list function setMerkleTreeRoot(bytes32 newMerkleTreeRoot) external onlyOwner { _setMerkleTreeRoot(newMerkleTreeRoot); } /// @notice set the max amount of gen 0 tokens function setPaidTokens(uint256 _PAID_TOKENS) external onlyOwner { require(PAID_TOKENS != _PAID_TOKENS, "NO_CHANGES"); PAID_TOKENS = _PAID_TOKENS; } /// @notice pause/unpause mintWithEthPresale function function setMintWithEthPresalePaused(bool paused) external onlyOwner { require(paused != mintWithEthPresalePaused, "NO_CHANGES"); mintWithEthPresalePaused = paused; } /// @notice pause/unpause mintWithEth function function setMintWithEthPaused(bool paused) external onlyOwner { require(paused != mintWithEthPaused, "NO_CHANGES"); mintWithEthPaused = paused; } /// @notice pause/unpause mintFromController function function setMintFromControllerPaused(bool paused) external onlyOwner { require(paused != mintFromControllerPaused, "NO_CHANGES"); mintFromControllerPaused = paused; } /// @notice pause/unpause token reveal functions function setRevealPaused(bool paused) external onlyOwner { require(paused != revealPaused, "NO_CHANGES"); revealPaused = paused; } /// @notice set the contract for the traits rendering /// @param _traits the contract address function setTraits(address _traits) external onlyOwner { traits = ITraits(_traits); } /// @notice add controller authority to an address /// @param _controller address to the game controller function addController(address _controller) external onlyOwner { controllers[_controller] = true; } /// @notice remove controller authority from an address /// @param _controller address to the game controller function removeController(address _controller) external onlyOwner { controllers[_controller] = false; } /// ==== Withdraw /// @notice withdraw the ether from the contract function withdraw() external onlyOwner { uint256 contractBalance = address(this).balance; // solhint-disable-next-line avoid-low-level-calls (bool sent, ) = splitter.call{value: contractBalance}(""); require(sent, "FAILED_TO_WITHDRAW"); } /// @notice withdraw ERC20 tokens from the contract /// people always randomly transfer ERC20 tokens to the /// @param erc20TokenAddress the ERC20 token address /// @param recipient who will get the tokens /// @param amount how many tokens function withdrawERC20( address erc20TokenAddress, address recipient, uint256 amount ) external onlyOwner { IERC20 erc20Contract = IERC20(erc20TokenAddress); bool sent = erc20Contract.transfer(recipient, amount); require(sent, "ERC20_WITHDRAW_FAILED"); } /// @notice reserve some tokens for the team. Can only reserve gen 0 tokens /// we also need token 0 to so ssetup market places befor mint function reserve(address to, uint256 amount) external onlyOwner { require(totalSupply() + amount < PAID_TOKENS); uint256 supply = totalSupply(); for (uint8 i = 0; i < amount; i++) { uint256 tokenId = supply + i; _safeMint(to, tokenId); } } /// @notice delete all entries in the seeds and seedTokenBoundaries arrays /// just in case something weird happens function cleanSeeds() external onlyOwner { require(seeds.length > 0, "NO_SEEDS"); for (uint256 i = 0; i < seeds.length; i++) { delete seeds[i]; delete seedTokenBoundaries[i]; } } /// @notice set the price for requesting a random number to Chainlink VRF /// Note that the base link token has 18 zeroes. function setVRFPrice(uint256 _LINK_VRF_PRICE) external onlyOwner { require(_LINK_VRF_PRICE != LINK_VRF_PRICE, "NO_CHANGES"); LINK_VRF_PRICE = _LINK_VRF_PRICE; } /// @notice owner request reveal seed, just in case something goes wrong function requestRevealSeed() external onlyOwner { requestRandomness(KEY_HASH, LINK_VRF_PRICE); } /// ==== IVampireGameControls Overrides /// @notice see {IVampireGameControls.mintFromController(receiver, amount)} function mintFromController(address receiver, uint256 amount) external override { require(!mintFromControllerPaused, "MINT_FROM_CONTROLLER_PAUSED"); require(controllers[_msgSender()], "NOT_AUTHORIZED"); require(totalSupply() + amount <= MAX_SUPPLY, "NOT_ENOUGH_TOKENS"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = totalSupply(); _safeMint(receiver, tokenId); } } /// @notice for a game controller to reveal the metadata of multiple token ids function controllerRevealTokens( uint256[] calldata tokenIds, uint256[] calldata _seeds ) external override onlyControllers { require(!revealPaused, "REVEAL_PAUSED"); require( tokenIds.length == seeds.length, "INPUTS_SHOULD_HAVE_SAME_LENGTH" ); for (uint256 i = 0; i < tokenIds.length; i++) { _revealToken(tokenIds[i], _seeds[i]); } } /// ==== IVampireGame Overrides /// @notice see {IVampireGame.getGenZeroSupply()} function getGenZeroSupply() external view override returns (uint256) { return PAID_TOKENS; } /// @notice see {IVampireGame.getMaxSupply()} function getMaxSupply() external view override returns (uint256) { return MAX_SUPPLY; } /// @notice see {IVampireGame.getTokenTraits(tokenId)} function getTokenTraits(uint256 tokenId) external view override returns (TokenTraits memory) { return tokenTraits[tokenId]; } /// @notice see {IVampireGame.isTokenRevealed(tokenId)} function isTokenRevealed(uint256 tokenId) public view override returns (bool) { return tokenTraits[tokenId].exists; } /// ==== ERC721 Overrides function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode approval of game controllers if (!controllers[_msgSender()]) require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return traits.tokenURI(tokenId); } /// ==== Chainlink VRF Overrides /// @notice Fulfills randomness from Chainlink VRF /// @param requestId returned id of VRF request /// @param randomness random number from VRF function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { uint256 minted = totalSupply(); // the amount of tokens minted has to be greater than the latest recorded // seed boundary, otherwise it means that there is already a seed for tokens // up to the current amount of tokens if ( seedTokenBoundaries.length == 0 || minted > seedTokenBoundaries[seedTokenBoundaries.length - 1] ) { seeds.push(randomness); seedTokenBoundaries.push(minted); } // Otherwise we discard the number. I'm hoping this doesn't happen though :D // More info: I'm hoping that this won't happen bevause we'll only ask for seeds // on spaced enough intervals, but not guaranteeing it in the contract } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /// @title AllowList /// @notice Adds simple merkle-tree based allow-list functionality to a contract. contract AllowList { /// @notice stores the Merkle Tree root. bytes32 internal _merkleTreeRoot; /// @notice Sets the new merkle tree root /// @param newMerkleTreeRoot the new root of the merkle tree function _setMerkleTreeRoot(bytes32 newMerkleTreeRoot) internal { require(_merkleTreeRoot != newMerkleTreeRoot, "NO_CHANGES"); _merkleTreeRoot = newMerkleTreeRoot; } /// @notice test if an address is part of the merkle tree /// @param _address the address to verify /// @param proof array of other hashes for proof calculation /// @return true if the address is part of the merkle tree function isAddressInAllowList(address _address, bytes32[] calldata proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(_address)); return MerkleProof.verify(proof, _merkleTreeRoot, leaf); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; struct TokenTraits { /// @dev every initialised token should have this as true /// this is just used to check agains a non-initialized struct bool exists; bool isVampire; // Shared Traits uint8 skin; uint8 face; uint8 clothes; // Human-only Traits uint8 pants; uint8 boots; uint8 accessory; uint8 hair; // Vampire-only Traits uint8 cape; uint8 predatorIndex; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./traits/TokenTraits.sol"; /// @notice Interface to interact with the VampireGame contract interface IVampireGame { /// @notice get the total supply of gen-0 function getGenZeroSupply() external view returns (uint256); /// @notice get the total supply of tokens function getMaxSupply() external view returns (uint256); /// @notice get the TokenTraits for a given tokenId function getTokenTraits(uint256 tokenId) external view returns (TokenTraits memory); /// @notice returns true if a token is aleady revealed function isTokenRevealed(uint256 tokenId) external view returns (bool); } /// @notice Interface to control parts of the VampireGame ERC 721 interface IVampireGameControls { /// @notice mint any amount of nft to any address /// Requirements: /// - message sender should be an allowed address (game contract) /// - amount + totalSupply() has to be smaller than MAX_SUPPLY function mintFromController(address receiver, uint256 amount) external; /// @notice reveal a list of tokens using specific seeds for each function controllerRevealTokens(uint256[] calldata tokenIds, uint256[] calldata _seeds) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; 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"); (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"); (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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } }
@notice set the price for requesting a random number to Chainlink VRF Note that the base link token has 18 zeroes.
function setVRFPrice(uint256 _LINK_VRF_PRICE) external onlyOwner { require(_LINK_VRF_PRICE != LINK_VRF_PRICE, "NO_CHANGES"); LINK_VRF_PRICE = _LINK_VRF_PRICE; }
2,475,675
[ 1, 542, 326, 6205, 364, 18709, 279, 2744, 1300, 358, 7824, 1232, 776, 12918, 3609, 716, 326, 1026, 1692, 1147, 711, 6549, 3634, 281, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 10986, 42, 5147, 12, 11890, 5034, 389, 10554, 67, 10986, 42, 67, 7698, 1441, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 10554, 67, 10986, 42, 67, 7698, 1441, 480, 22926, 67, 10986, 42, 67, 7698, 1441, 16, 315, 3417, 67, 1792, 3388, 3991, 8863, 203, 3639, 22926, 67, 10986, 42, 67, 7698, 1441, 273, 389, 10554, 67, 10986, 42, 67, 7698, 1441, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.6 <=0.8.3; contract Game { // players info address public gameOwner; address internal gameOpponent; struct player { uint8 number; // player 1 or 2 address ethAddress; } // game info struct game { uint8 playerCounter; uint8 roundCounter; } bytes1 firstPlayer; uint256 bet; constructor() public payable { require(msg.value > 0.1 ether); } // events // functions // pretty basic: https://github.com/buddies2705/dice/tree/master/contracts function createGame(uint256 _bet) public { gameOwner = msg.sender; bet = _bet; } function joinGame(address _opponent) public returns (bool) { if (gameOpponent == address(0)) { gameOpponent = _opponent; } else { return false; // "Game is already full"; } chooseFirstPlayer(); } function chooseFirstPlayer() public { // this should call the random number generator to get a 1 or 2 // uint8 rnd; // firstPlayer = gameOwner; // if (rnd == 2) { // firstPlayer = gameOpponent; // } } function incrementRound() internal {} function rollDice() public view returns (uint256) { // this should call the random number generator to get a number from 1 to 6 } function gameOptions(address _player, bytes32 _option) public { // set the options [raise, call, fold] for the given player } function raiseBet() public {} function callGame() public {} function foldGame() public {} }
functions pretty basic: https:github.com/buddies2705/dice/tree/master/contracts
function createGame(uint256 _bet) public { gameOwner = msg.sender; bet = _bet; }
2,565,457
[ 1, 10722, 7517, 5337, 30, 2333, 30, 6662, 18, 832, 19, 70, 20567, 606, 5324, 6260, 19, 72, 1812, 19, 3413, 19, 7525, 19, 16351, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 12496, 12, 11890, 5034, 389, 70, 278, 13, 1071, 288, 203, 3639, 7920, 5541, 273, 1234, 18, 15330, 31, 203, 3639, 2701, 273, 389, 70, 278, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; interface ICPO { function implementations(string memory) external view returns (address); } interface IDestroyable { function destroy() external; } /* // https://forum.openzeppelin.com/t/a-more-gas-efficient-upgradeable-proxy-by-not-using-storage/4111/ // Not using SLOAD for implementation retrieval This is an upgrade on the original implementation listed above. This helps shave off even more gas by removing the need for a "Beacon" and extracing out the immutable address. Upgradable control flow: 1. CPO --create2--> Proxy 2. On creation, Proxy gets the implementation from CPO and writes impl address into immutable variable - Immutable variable is stored at contract code offset 376 - Compiled with solc 0.8.10, optimization runs: (?) depends on forge 3. To upgrade, destroy the proxy and recreate it with the same salt */ contract Proxy { address public immutable logic; address public immutable cpo; // If you ever change this file // Or recompile with a new compiler, this offset will probably be different // Run test_get_offset() with 3 verbosity to get the offset uint256 internal constant offset = 441; constructor(address _cpo, string memory _name) { cpo = _cpo; logic = ICPO(_cpo).implementations(_name); } function destroy() public { require(msg.sender == cpo, "shoo"); address _addr = payable(cpo); assembly { selfdestruct(_addr) } } receive() external payable {} fallback() external payable { assembly { // Extract out immutable variable "logic" codecopy(0, offset, 20) let impl := mload(0) switch iszero(impl) case 1 { revert(0, 0) } default { } calldatacopy(0, 0, calldatasize()) let result := delegatecall( gas(), shr(96, impl), 0, calldatasize(), 0, 0 ) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } contract CPO { // **** State variables **** address public owner; mapping(string => address) public implementations; mapping(string => address) public proxies; // **** Events **** event ProxyDeployed(address addr, bytes32 salt, address logic); // **** Constructor + Modifiers **** // receive() external payable {} constructor(address _owner) { owner = _owner; } modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } // **** Public functions **** function proxyCreationCode(string memory name) public view returns (bytes memory) { return abi.encodePacked( // type(Proxy).creationCode, hex"60c060405234801561001057600080fd5b5060405161072a38038061072a833981810160405281019061003291906102f6565b8173ffffffffffffffffffffffffffffffffffffffff1660a08173ffffffffffffffffffffffffffffffffffffffff16815250508173ffffffffffffffffffffffffffffffffffffffff16630618f104826040518263ffffffff1660e01b815260040161009f91906103a7565b602060405180830381865afa1580156100bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e091906103c9565b73ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff168152505050506103f6565b6000604051905090565b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006101598261012e565b9050919050565b6101698161014e565b811461017457600080fd5b50565b60008151905061018681610160565b92915050565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6101df82610196565b810181811067ffffffffffffffff821117156101fe576101fd6101a7565b5b80604052505050565b600061021161011a565b905061021d82826101d6565b919050565b600067ffffffffffffffff82111561023d5761023c6101a7565b5b61024682610196565b9050602081019050919050565b60005b83811015610271578082015181840152602081019050610256565b83811115610280576000848401525b50505050565b600061029961029484610222565b610207565b9050828152602081018484840111156102b5576102b4610191565b5b6102c0848285610253565b509392505050565b600082601f8301126102dd576102dc61018c565b5b81516102ed848260208601610286565b91505092915050565b6000806040838503121561030d5761030c610124565b5b600061031b85828601610177565b925050602083015167ffffffffffffffff81111561033c5761033b610129565b5b610348858286016102c8565b9150509250929050565b600081519050919050565b600082825260208201905092915050565b600061037982610352565b610383818561035d565b9350610393818560208601610253565b61039c81610196565b840191505092915050565b600060208201905081810360008301526103c1818461036e565b905092915050565b6000602082840312156103df576103de610124565b5b60006103ed84828501610177565b91505092915050565b60805160a0516103026104286000396000818160f70152818161018701526101d1015260006101ad01526103026000f3fe6080604052600436106100385760003560e01c806383197ef014610088578063d7dfa0dd1461009f578063f3a50f89146100ca5761003f565b3661003f57005b60146101b96000396000518015600181146100595761005e565b600080fd5b5036600080376000803660008460601c5af43d6000803e8060008114610083573d6000f35b3d6000fd5b34801561009457600080fd5b5061009d6100f5565b005b3480156100ab57600080fd5b506100b46101ab565b6040516100c19190610234565b60405180910390f35b3480156100d657600080fd5b506100df6101cf565b6040516100ec9190610234565b60405180910390f35b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610183576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161017a906102ac565b60405180910390fd5b60007f0000000000000000000000000000000000000000000000000000000000000000905080ff5b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061021e826101f3565b9050919050565b61022e81610213565b82525050565b60006020820190506102496000830184610225565b92915050565b600082825260208201905092915050565b7f73686f6f00000000000000000000000000000000000000000000000000000000600082015250565b600061029660048361024f565b91506102a182610260565b602082019050919050565b600060208201905081810360008301526102c581610289565b905091905056fea2646970667358221220b4f3dfa57797c7ace04ab12b59deeef762aa067debba1b2ce7e71677c10ae92864736f6c634300080a0033", abi.encode(address(this), name) ); } function proxyInitCodeHash(string memory name) public view returns (bytes32) { return keccak256(proxyCreationCode(name)); } // **** Restricted functions **** function createProxy( string memory name, bytes32 salt, address impl ) public onlyOwner returns (address) { require(proxies[name] == address(0), "Proxy not destroyed yet"); // Since proxy reads implementation address from this contract // we need to mutate the impl state first implementations[name] = impl; address deployed; bytes memory bytecode = proxyCreationCode(name); assembly { deployed := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(deployed != address(0), "create2 failed"); proxies[name] = deployed; emit ProxyDeployed(deployed, salt, implementations[name]); return deployed; } function destroyProxy(string memory name) public onlyOwner { require(proxies[name] != address(0), "Proxy doesn't exist"); IDestroyable(proxies[name]).destroy(); proxies[name] = address(0); } function transferOwnership(address newOwner) public onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); owner = newOwner; } }
type(Proxy).creationCode,
function proxyCreationCode(string memory name) public view returns (bytes memory) { return abi.encodePacked( hex"60c060405234801561001057600080fd5b5060405161072a38038061072a833981810160405281019061003291906102f6565b8173ffffffffffffffffffffffffffffffffffffffff1660a08173ffffffffffffffffffffffffffffffffffffffff16815250508173ffffffffffffffffffffffffffffffffffffffff16630618f104826040518263ffffffff1660e01b815260040161009f91906103a7565b602060405180830381865afa1580156100bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e091906103c9565b73ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff168152505050506103f6565b6000604051905090565b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006101598261012e565b9050919050565b6101698161014e565b811461017457600080fd5b50565b60008151905061018681610160565b92915050565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6101df82610196565b810181811067ffffffffffffffff821117156101fe576101fd6101a7565b5b80604052505050565b600061021161011a565b905061021d82826101d6565b919050565b600067ffffffffffffffff82111561023d5761023c6101a7565b5b61024682610196565b9050602081019050919050565b60005b83811015610271578082015181840152602081019050610256565b83811115610280576000848401525b50505050565b600061029961029484610222565b610207565b9050828152602081018484840111156102b5576102b4610191565b5b6102c0848285610253565b509392505050565b600082601f8301126102dd576102dc61018c565b5b81516102ed848260208601610286565b91505092915050565b6000806040838503121561030d5761030c610124565b5b600061031b85828601610177565b925050602083015167ffffffffffffffff81111561033c5761033b610129565b5b610348858286016102c8565b9150509250929050565b600081519050919050565b600082825260208201905092915050565b600061037982610352565b610383818561035d565b9350610393818560208601610253565b61039c81610196565b840191505092915050565b600060208201905081810360008301526103c1818461036e565b905092915050565b6000602082840312156103df576103de610124565b5b60006103ed84828501610177565b91505092915050565b60805160a0516103026104286000396000818160f70152818161018701526101d1015260006101ad01526103026000f3fe6080604052600436106100385760003560e01c806383197ef014610088578063d7dfa0dd1461009f578063f3a50f89146100ca5761003f565b3661003f57005b60146101b96000396000518015600181146100595761005e565b600080fd5b5036600080376000803660008460601c5af43d6000803e8060008114610083573d6000f35b3d6000fd5b34801561009457600080fd5b5061009d6100f5565b005b3480156100ab57600080fd5b506100b46101ab565b6040516100c19190610234565b60405180910390f35b3480156100d657600080fd5b506100df6101cf565b6040516100ec9190610234565b60405180910390f35b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610183576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161017a906102ac565b60405180910390fd5b60007f0000000000000000000000000000000000000000000000000000000000000000905080ff5b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061021e826101f3565b9050919050565b61022e81610213565b82525050565b60006020820190506102496000830184610225565b92915050565b600082825260208201905092915050565b7f73686f6f00000000000000000000000000000000000000000000000000000000600082015250565b600061029660048361024f565b91506102a182610260565b602082019050919050565b600060208201905081810360008301526102c581610289565b905091905056fea2646970667358221220b4f3dfa57797c7ace04ab12b59deeef762aa067debba1b2ce7e71677c10ae92864736f6c634300080a0033", abi.encode(address(this), name) ); }
1,832,766
[ 1, 723, 12, 3886, 2934, 17169, 1085, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2889, 9906, 1085, 12, 1080, 3778, 508, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 3778, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 3827, 6, 4848, 71, 7677, 3028, 6260, 4366, 8875, 1611, 4313, 6625, 21661, 6669, 3784, 3672, 8313, 25, 70, 3361, 26, 3028, 6260, 2313, 2163, 9060, 69, 23, 3672, 23, 3672, 26, 2163, 9060, 69, 28, 3707, 10689, 2643, 15168, 26, 3028, 6260, 6030, 15168, 29, 7677, 6625, 1578, 29, 3657, 7677, 20481, 74, 26, 4313, 25, 70, 28, 31331, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 2313, 4848, 69, 6840, 31331, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 23329, 3600, 26520, 3361, 28, 31331, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 2313, 4449, 7677, 2643, 74, 2163, 8875, 5558, 3028, 6260, 28246, 4449, 9460, 9460, 2313, 4848, 73, 1611, 70, 28, 3600, 5558, 26565, 24171, 6625, 29, 74, 29, 3657, 7677, 23494, 69, 27, 4313, 25, 70, 26, 3103, 7677, 3028, 6260, 2643, 6840, 23, 4630, 28, 2643, 9222, 69, 507, 25984, 1611, 4313, 6625, 13459, 25, 9036, 72, 26, 3784, 3672, 23, 73, 23, 72, 26, 3784, 8313, 25, 70, 3361, 3361, 3361, 3361, 26, 3028, 6260, 3437, 72, 26, 1611, 74, 28644, 1611, 74, 28, 6734, 23329, 18585, 26, 3028, 6260, 2947, 6840, 15168, 29, 7677, 6625, 73, 5908, 3657, 7677, 23494, 71, 29, 4313, 25, 70, 9036, 9460, 9460, 9460, 9460, 9460, 2 ]
pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } /** * Phat Cats - Crypto-Cards * - https://crypto-cards.io * - https://phatcats.co * * Copyright 2019 (c) Phat Cats, Inc. */ /** * @title Crypto-Cards Payroll */ contract CryptoCardsPayroll is Ownable, ReentrancyGuard { using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event PayeeUpdated(address account, uint256 sharesAdded, uint256 totalShares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; uint256 private _totalReleasedAllTime; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Constructor */ constructor () public {} /** * @dev payable fallback */ function () external payable { emit PaymentReceived(msg.sender, msg.value); } /** * @return the total shares of the contract. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @return the total amount already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @return the total amount already released. */ function totalReleasedAllTime() public view returns (uint256) { return _totalReleasedAllTime; } /** * @return the total amount of funds in the contract. */ function totalFunds() public view returns (uint256) { return address(this).balance; } /** * @return the shares of an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @return the shares of an account. */ function sharePercentage(address account) public view returns (uint256) { if (_totalShares == 0 || _shares[account] == 0) { return 0; } return _shares[account].mul(100).div(_totalShares); } /** * @return the amount already released to an account. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @return the amount available for release to an account. */ function available(address account) public view returns (uint256) { uint256 totalReceived = address(this).balance.add(_totalReleased); uint256 totalCut = totalReceived.mul(_shares[account]).div(_totalShares); if (block.number < _released[account]) { return 0; } //injected CONTRACT AFFECTED BY MINERS return totalCut.sub(_released[account]); } /** * @return the address of a payee. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Release payee's proportional payment. */ function release() external nonReentrant { address payable account = address(uint160(msg.sender)); require(_shares[account] > 0, "Account not eligible for payroll"); uint256 payment = available(account); require(payment != 0, "No payment available for account"); _release(account, payment); } /** * @dev Release payment for all payees and reset state */ function releaseAll() public onlyOwner { _releaseAll(); _resetAll(); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function addNewPayee(address account, uint256 shares_) public onlyOwner { require(account != address(0), "Invalid account"); require(Address.isContract(account) == false, "Account cannot be a contract"); require(shares_ > 0, "Shares must be greater than zero"); require(_shares[account] == 0, "Payee already exists"); require(_totalReleased == 0, "Must release all existing payments first"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares.add(shares_); emit PayeeAdded(account, shares_); } /** * @dev Increase he shares of an existing payee * @param account The address of the payee to increase. * @param shares_ The number of shares to add to the payee. */ function increasePayeeShares(address account, uint256 shares_) public onlyOwner { require(account != address(0), "Invalid account"); require(shares_ > 0, "Shares must be greater than zero"); require(_shares[account] > 0, "Payee does not exist"); require(_totalReleased == 0, "Must release all existing payments first"); _shares[account] = _shares[account].add(shares_); _totalShares = _totalShares.add(shares_); emit PayeeUpdated(account, shares_, _shares[account]); } /** * @dev Release one of the payee's proportional payment. * @param account Whose payments will be released. */ function _release(address payable account, uint256 payment) private { _released[account] = _released[account].add(payment); _totalReleased = _totalReleased.add(payment); _totalReleasedAllTime = _totalReleasedAllTime.add(payment); account.transfer(payment); emit PaymentReleased(account, payment); } /** * @dev Release payment for all payees */ function _releaseAll() private { for (uint256 i = 0; i < _payees.length; i++) { _release(address(uint160(_payees[i])), available(_payees[i])); } } /** * @dev Reset state of released payments for all payees */ function _resetAll() private { for (uint256 i = 0; i < _payees.length; i++) { _released[_payees[i]] = 0; } _totalReleased = 0; } }
* @return the total amount of funds in the contract./
function totalFunds() public view returns (uint256) { return address(this).balance; }
14,066,565
[ 1, 2463, 326, 2078, 3844, 434, 284, 19156, 316, 326, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 42, 19156, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1758, 12, 2211, 2934, 12296, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.10; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Errors.sol"; import "./interfaces/ICellarStaking.sol"; /** * @title Sommelier Staking * @author Kevin Kennis * * Staking for Sommelier Cellars. * * This contract is inspired by the Synthetix staking rewards contract, Ampleforth's * token geyser, and Treasure DAO's MAGIC mine. However, there are unique improvements * and new features, specifically unbonding, as inspired by LP bonding on Osmosis. * Unbonding allows the contract to guarantee deposits for a certain amount of time, * increasing predictability and stickiness of TVL for Cellars. * * *********************************** Funding Flow *********************************** * * 1) The contract owner calls 'notifyRewardAmount' to specify an initial schedule of rewards * The contract collects the distribution token from the owner to fund the * specified reward schedule, where the length of the reward schedule is defined by * epochDuration. This duration can also be changed by the owner, and any change will apply * to future calls to 'notifyRewardAmount' (but will not affect active schedules). * 2) At a future time, the contract owner may call 'notifyRewardAmount' again to extend the * staking program with new rewards. These new schedules may distribute more or less * rewards than previous epochs. If a previous epoch is not finished, any leftover rewards * get rolled into the new schedule, increasing the reward rate. Reward schedules always * end exactly 'epochDuration' seconds from the most recent time 'notifyRewardAmount' has been * called. * * ********************************* Staking Lifecycle ******************************** * * 1) A user may deposit a certain amount of tokens to stake, and is required to lock * those tokens for a specified amount of time. There are three locking options: * one day, one week, or one month. Longer locking times receive larger 'boosts', * that the deposit will receive a larger proportional amount of shares. A user * may not unstake until they choose to unbond, and time defined by the lock has * elapsed during unbonding. * 2) When a user wishes to withdraw, they must first "unbond" their stake, which starts * a timer equivalent to the lock time. They still receive their rewards during this * time, but forfeit any locktime boosts. A user may cancel the unbonding period at any * time to regain their boosts, which will set the unbonding timer back to 0. * 2) Once the lock has elapsed, a user may unstake their deposit, either partially * or in full. The user will continue to receive the same 'boosted' amount of rewards * until they unstake. The user may unstake all of their deposits at once, as long * as all of the lock times have elapsed. When unstaking, the user will also receive * all eligible rewards for all deposited stakes, which accumulate linearly. * 3) At any time, a user may claim their available rewards for their deposits. Rewards * accumulate linearly and can be claimed at any time, whether or not the lock has * for a given deposit has expired. The user can claim rewards for a specific deposit, * or may choose to collect all eligible rewards at once. * * ************************************ Accounting ************************************ * * The contract uses an accounting mechanism based on the 'rewardPerToken' model, * originated by the Synthetix staking rewards contract. First, token deposits are accounted * for, with synthetic "boosted" amounts used for reward calculations. As time passes, * rewardPerToken continues to accumulate, whereas the value of 'rewardPerToken' will match * the reward due to a single token deposited before the first ever rewards were scheduled. * * At each accounting checkpoint, rewardPerToken will be recalculated, and every time an * existing stake is 'touched', this value is used to calculate earned rewards for that * stake. Each stake tracks a 'rewardPerTokenPaid' value, which represents the 'rewardPerToken' * value the last time the stake calculated "earned" rewards. Every recalculation pays the difference. * This ensures no earning is double-counted. When a new stake is deposited, its * initial 'rewardPerTokenPaid' is set to the current 'rewardPerToken' in the contract, * ensuring it will not receive any rewards emitted during the period before deposit. * * The following example applies to a given epoch of 100 seconds, with a reward rate * of 100 tokens per second: * * a) User 1 deposits a stake of 50 before the epoch begins * b) User 2 deposits a stake of 20 at second 20 of the epoch * c) User 3 deposits a stake of 100 at second 50 of the epoch * * In this case, * * a) At second 20, before User 2's deposit, rewardPerToken will be 40 * (2000 total tokens emitted over 20 seconds / 50 staked). * b) At second 50, before User 3's deposit, rewardPerToken will be 82.857 * (previous 40 + 3000 tokens emitted over 30 seconds / 70 staked == 42.857) * c) At second 100, when the period is over, rewardPerToken will be 112.267 * (previous 82.857 + 5000 tokens emitted over 50 seconds / 170 staked == 29.41) * * * Then, each user will receive rewards proportional to the their number of tokens. At second 100: * a) User 1 will receive 50 * 112.267 = 5613.35 rewards * b) User 2 will receive 20 * (112.267 - 40) = 1445.34 * (40 is deducted because it was the current rewardPerToken value on deposit) * c) User 3 will receive 100 * (112.267 - 82.857) = 2941 * (82.857 is deducted because it was the current rewardPerToken value on deposit) * * Depending on deposit times, this accumulation may take place over multiple * reward periods, and the total rewards earned is simply the sum of rewards earned for * each period. A user may also have multiple discrete deposits, which are all * accounted for separately due to timelocks and locking boosts. Therefore, * a user's total earned rewards are a function of their rewards across * the proportional tokens deposited, across different ranges of rewardPerToken. * * Reward accounting takes place before every operation which may change * accounting calculations (minting of new shares on staking, burning of * shares on unstaking, or claiming, which decrements eligible rewards). * This is gas-intensive but unavoidable, since retroactive accounting * based on previous proportionate shares would require a prohibitive * amount of storage of historical state. On every accounting run, there * are a number of safety checks to ensure that all reward tokens are * accounted for and that no accounting time periods have been missed. * */ contract CellarStaking is ICellarStaking, Ownable { using SafeERC20 for ERC20; // ============================================ STATE ============================================== // ============== Constants ============== uint256 public constant ONE = 1e18; uint256 public constant ONE_DAY = 60 * 60 * 24; uint256 public constant ONE_WEEK = ONE_DAY * 7; uint256 public constant TWO_WEEKS = ONE_WEEK * 2; uint256 public constant MAX_UINT = 2**256 - 1; uint256 public immutable SHORT_BOOST; uint256 public immutable MEDIUM_BOOST; uint256 public immutable LONG_BOOST; uint256 public immutable SHORT_BOOST_TIME; uint256 public immutable MEDIUM_BOOST_TIME; uint256 public immutable LONG_BOOST_TIME; // ============ Global State ============= ERC20 public immutable override stakingToken; ERC20 public immutable override distributionToken; uint256 public override epochDuration; uint256 public override minimumDeposit; uint256 public override endTimestamp; uint256 public override totalDeposits; uint256 public override totalDepositsWithBoost; uint256 public override rewardRate; uint256 public override rewardPerTokenStored; uint256 private lastAccountingTimestamp = block.timestamp; /// @notice Emergency states in case of contract malfunction. bool public override paused; bool public override ended; bool public override claimable; /// @notice Tracks if an address can call notifyReward() mapping(address => bool) public override isRewardDistributor; // ============= User State ============== /// @notice user => all user's staking positions mapping(address => UserStake[]) public stakes; // ========================================== CONSTRUCTOR =========================================== /** * @param _owner The owner of the staking contract - will immediately receive ownership. * @param _rewardsDistribution The address allowed to schedule new rewards. * @param _stakingToken The token users will deposit in order to stake. * @param _distributionToken The token the staking contract will distribute as rewards. * @param _epochDuration The length of a reward schedule. */ constructor( address _owner, address _rewardsDistribution, ERC20 _stakingToken, ERC20 _distributionToken, uint256 _epochDuration, uint256 shortBoost, uint256 mediumBoost, uint256 longBoost, uint256 shortBoostTime, uint256 mediumBoostTime, uint256 longBoostTime ) { stakingToken = _stakingToken; isRewardDistributor[_rewardsDistribution] = true; distributionToken = _distributionToken; epochDuration = _epochDuration; SHORT_BOOST = shortBoost; MEDIUM_BOOST = mediumBoost; LONG_BOOST = longBoost; SHORT_BOOST_TIME = shortBoostTime; MEDIUM_BOOST_TIME = mediumBoostTime; LONG_BOOST_TIME = longBoostTime; transferOwnership(_owner); } // ======================================= STAKING OPERATIONS ======================================= /** * @notice Make a new deposit into the staking contract. Longer locks receive reward boosts. * @dev Specified amount of stakingToken must be approved for withdrawal by the caller. * @dev Valid lock values are 0 (one day), 1 (one week), and 2 (two weeks). * * @param amount The amount of the stakingToken to stake. * @param lock The amount of time to lock stake for. */ function stake(uint256 amount, Lock lock) external override whenNotPaused updateRewards { if (amount == 0) revert USR_ZeroDeposit(); if (amount < minimumDeposit) revert USR_MinimumDeposit(amount, minimumDeposit); if (block.timestamp > endTimestamp) revert STATE_NoRewardsLeft(); // Do share accounting and populate user stake information (uint256 boost, ) = _getBoost(lock); uint256 amountWithBoost = amount + ((amount * boost) / ONE); stakes[msg.sender].push(UserStake({ amount: amount, amountWithBoost: amountWithBoost, rewardPerTokenPaid: rewardPerTokenStored, rewards: 0, unbondTimestamp: 0, lock: lock })); // Update global state totalDeposits += amount; totalDepositsWithBoost += amountWithBoost; stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Stake(msg.sender, stakes[msg.sender].length - 1, amount); } /** * @notice Unbond a specified amount from a certain deposited stake. * @dev After the unbond time elapses, the deposit can be unstaked. * * @param depositId The specified deposit to unstake from. * */ function unbond(uint256 depositId) external override whenNotPaused updateRewards { _unbond(depositId); } /** * @notice Unbond all user deposits. * @dev Different deposits may have different timelocks. * */ function unbondAll() external override whenNotPaused updateRewards { // Individually unbond each deposit UserStake[] storage userStakes = stakes[msg.sender]; for (uint256 i = 0; i < userStakes.length; i++) { UserStake storage s = userStakes[i]; if (s.amount != 0 && s.unbondTimestamp == 0) { _unbond(i); } } } /** * @dev Contains all logic for processing an unbond operation. * For the given deposit, sets an unlock time, and * reverts boosts to 0. * * @param depositId The specified deposit to unbond from. */ function _unbond(uint256 depositId) internal { // Fetch stake and make sure it is withdrawable UserStake storage s = stakes[msg.sender][depositId]; uint256 depositAmount = s.amount; if (depositAmount == 0) revert USR_NoDeposit(depositId); if (s.unbondTimestamp > 0) revert USR_AlreadyUnbonding(depositId); _updateRewardForStake(msg.sender, depositId); // Remove any lock boosts uint256 depositAmountReduced = s.amountWithBoost - depositAmount; (, uint256 lockDuration) = _getBoost(s.lock); s.amountWithBoost = depositAmount; s.unbondTimestamp = block.timestamp + lockDuration; totalDepositsWithBoost -= depositAmountReduced; emit Unbond(msg.sender, depositId, depositAmount); } /** * @notice Cancel an unbonding period for a stake that is currently unbonding. * @dev Resets the unbonding timer and reinstates any lock boosts. * * @param depositId The specified deposit to unstake from. * */ function cancelUnbonding(uint256 depositId) external override whenNotPaused updateRewards { _cancelUnbonding(depositId); } /** * @notice Cancel an unbonding period for all stakes. * @dev Only cancels stakes that are unbonding. * */ function cancelUnbondingAll() external override whenNotPaused updateRewards { // Individually unbond each deposit UserStake[] storage userStakes = stakes[msg.sender]; for (uint256 i = 0; i < userStakes.length; i++) { UserStake storage s = userStakes[i]; if (s.amount != 0 && s.unbondTimestamp != 0) { _cancelUnbonding(i); } } } /** * @dev Contains all logic for cancelling an unbond operation. * For the given deposit, resets the unbonding timer, and * reverts boosts to amount determined by lock. * * @param depositId The specified deposit to unbond from. */ function _cancelUnbonding(uint256 depositId) internal { // Fetch stake and make sure it is withdrawable UserStake storage s = stakes[msg.sender][depositId]; uint256 depositAmount = s.amount; if (depositAmount == 0) revert USR_NoDeposit(depositId); if (s.unbondTimestamp == 0) revert USR_NotUnbonding(depositId); _updateRewardForStake(msg.sender, depositId); // Reinstate (uint256 boost, ) = _getBoost(s.lock); uint256 amountWithBoost = s.amount + (s.amount * boost) / ONE; uint256 depositAmountIncreased = amountWithBoost - s.amountWithBoost; s.amountWithBoost = amountWithBoost; s.unbondTimestamp = 0; totalDepositsWithBoost += depositAmountIncreased; emit CancelUnbond(msg.sender, depositId); } /** * @notice Unstake a specific deposited stake. * @dev The unbonding time for the specified deposit must have elapsed. * @dev Unstaking automatically claims available rewards for the deposit. * * @param depositId The specified deposit to unstake from. * * @return reward The amount of accumulated rewards since the last reward claim. */ function unstake(uint256 depositId) external override whenNotPaused updateRewards returns (uint256 reward) { return _unstake(depositId); } /** * @notice Unstake all user deposits. * @dev Only unstakes rewards that are unbonded. * @dev Unstaking automatically claims all available rewards. * * @return rewards The amount of accumulated rewards since the last reward claim. */ function unstakeAll() external override whenNotPaused updateRewards returns (uint256[] memory) { // Individually unstake each deposit UserStake[] storage userStakes = stakes[msg.sender]; uint256[] memory rewards = new uint256[](userStakes.length); for (uint256 i = 0; i < userStakes.length; i++) { UserStake storage s = userStakes[i]; if (s.amount != 0 && s.unbondTimestamp != 0 && block.timestamp >= s.unbondTimestamp) { rewards[i] = _unstake(i); } } return rewards; } /** * @dev Contains all logic for processing an unstake operation. * For the given deposit, does share accounting and burns * shares, returns staking tokens to the original owner, * updates global deposit and share trackers, and claims * rewards for the given deposit. * * @param depositId The specified deposit to unstake from. */ function _unstake(uint256 depositId) internal returns (uint256 reward) { // Fetch stake and make sure it is withdrawable UserStake storage s = stakes[msg.sender][depositId]; uint256 depositAmount = s.amount; if (depositAmount == 0) revert USR_NoDeposit(depositId); if (s.unbondTimestamp == 0 || block.timestamp < s.unbondTimestamp) revert USR_StakeLocked(depositId); _updateRewardForStake(msg.sender, depositId); // Start unstaking uint256 amountWithBoost = s.amountWithBoost; reward = s.rewards; s.amount = 0; s.amountWithBoost = 0; s.rewards = 0; // Update global state totalDeposits -= depositAmount; totalDepositsWithBoost -= amountWithBoost; // Distribute stake stakingToken.safeTransfer(msg.sender, depositAmount); // Distribute reward distributionToken.safeTransfer(msg.sender, reward); emit Unstake(msg.sender, depositId, depositAmount, reward); } /** * @notice Claim rewards for a given deposit. * @dev Rewards accumulate linearly since deposit. * * @param depositId The specified deposit for which to claim rewards. * * @return reward The amount of accumulated rewards since the last reward claim. */ function claim(uint256 depositId) external override whenNotPaused updateRewards returns (uint256 reward) { return _claim(depositId); } /** * @notice Claim all available rewards. * @dev Rewards accumulate linearly. * * * @return rewards The amount of accumulated rewards since the last reward claim. * Each element of the array specified rewards for the corresponding * indexed deposit. */ function claimAll() external override whenNotPaused updateRewards returns (uint256[] memory rewards) { // Individually claim for each stake UserStake[] storage userStakes = stakes[msg.sender]; rewards = new uint256[](userStakes.length); for (uint256 i = 0; i < userStakes.length; i++) { rewards[i] = _claim(i); } } /** * @dev Contains all logic for processing a claim operation. * Relies on previous reward accounting done before * processing external functions. Updates the amount * of rewards claimed so rewards cannot be claimed twice. * * * @param depositId The specified deposit to claim rewards for. * * @return reward The amount of accumulated rewards since the last reward claim. */ function _claim(uint256 depositId) internal returns (uint256 reward) { // Fetch stake and make sure it is valid UserStake storage s = stakes[msg.sender][depositId]; _updateRewardForStake(msg.sender, depositId); reward = s.rewards; // Distribute reward if (reward > 0) { s.rewards = 0; distributionToken.safeTransfer(msg.sender, reward); emit Claim(msg.sender, depositId, reward); } } /** * @notice Unstake and return all staked tokens to the caller. * @dev In emergency mode, staking time locks do not apply. */ function emergencyUnstake() external override { if (!ended) revert STATE_NoEmergencyUnstake(); UserStake[] storage userStakes = stakes[msg.sender]; for (uint256 i = 0; i < userStakes.length; i++) { UserStake storage s = userStakes[i]; uint256 amount = s.amount; if (amount > 0) { s.amount = 0; stakingToken.transfer(msg.sender, amount); emit EmergencyUnstake(msg.sender, i, amount); } } } /** * @notice Claim any accumulated rewards in emergency mode. * @dev In emergency node, no additional reward accounting is done. * Rewards do not accumulate after emergency mode begins, * so any earned amount is only retroactive to when the contract * was active. */ function emergencyClaim() external override { if (!ended) revert STATE_NoEmergencyUnstake(); if (!claimable) revert STATE_NoEmergencyClaim(); uint256 reward; UserStake[] storage userStakes = stakes[msg.sender]; for (uint256 i = 0; i < userStakes.length; i++) { UserStake storage s = userStakes[i]; reward += s.rewards; s.rewards = 0; } if (reward > 0) { distributionToken.safeTransfer(msg.sender, reward); // No need for per-stake events like emergencyUnstake: // don't need to make sure positions were unwound emit EmergencyClaim(msg.sender, reward); } } // ======================================== ADMIN OPERATIONS ======================================== /** * @notice Specify a new schedule for staking rewards. * @dev Can only be called by reward distributor. Owner must approve distributionToken for withdrawal. * * @param reward The amount of rewards to distribute per second. */ function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateRewards { if (reward < epochDuration) revert USR_ZeroRewardsPerEpoch(); if (block.timestamp >= endTimestamp) { // Set new rate bc previous has already expired rewardRate = reward / epochDuration; } else { uint256 remaining = endTimestamp - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / epochDuration; } // prevent overflow when computing rewardPerToken if (rewardRate >= ((type(uint256).max / ONE) / epochDuration)) { revert USR_RewardTooLarge(); } endTimestamp = block.timestamp + epochDuration; // Source rewards distributionToken.safeTransferFrom(msg.sender, address(this), reward); emit Funding(reward, endTimestamp); } /** * @notice Change the length of a reward epoch for future reward schedules. * * @param _epochDuration The new duration for reward schedules. */ function setRewardsDuration(uint256 _epochDuration) external override onlyOwner { epochDuration = _epochDuration; emit EpochDurationChange(epochDuration); } /** * @notice Specify a minimum deposit for staking. * @dev Can only be called by owner. * * @param _minimum The minimum deposit for each new stake. */ function setMinimumDeposit(uint256 _minimum) external override onlyOwner { minimumDeposit = _minimum; } /** * @notice Pause the contract. Pausing prevents staking, unstaking, claiming * rewards, and scheduling new rewards. Should only be used * in an emergency. * * @param _paused Whether the contract should be paused. */ function setPaused(bool _paused) external override onlyOwner { paused = _paused; } /** * @notice Stops the contract - this is irreversible. Should only be used * in an emergency, for example an irreversible accounting bug * or an exploit. Enables all depositors to withdraw their stake * instantly. Also stops new rewards accounting. * * @param makeRewardsClaimable Whether any previously accumulated rewards should be claimable. */ function emergencyStop(bool makeRewardsClaimable) external override onlyOwner { if (ended) revert STATE_AlreadyStopped(); // Update state and put in irreversible emergency mode ended = true; claimable = makeRewardsClaimable; if (!claimable) { // Send distribution token back to owner distributionToken.transfer(msg.sender, distributionToken.balanceOf(address(this))); } emit EmergencyStop(msg.sender, makeRewardsClaimable); } /** * @notice Set the EOA or contract allowed to call 'notifyRewardAmount' to schedule * new rewards. * * @param _rewardsDistribution The new reward distributor. * @param _set Whether the address should be allowed to distribute. */ function setRewardsDistribution(address _rewardsDistribution, bool _set) external override onlyOwner { isRewardDistributor[_rewardsDistribution] = _set; emit DistributorSet(_rewardsDistribution, _set); } // ======================================= STATE INFORMATION ======================================= /** * @notice Returns the latest time to account for in the reward program. * * @return timestamp The latest time to calculate. */ function latestRewardsTimestamp() public view override returns (uint256) { return block.timestamp < endTimestamp ? block.timestamp : endTimestamp; } /** * @notice Returns the amount of reward to distribute per currently-depostied token. * Will update on changes to total deposit balance or reward rate. * @dev Sets rewardPerTokenStored. * * * @return rewardPerToken The latest time to calculate. */ function rewardPerToken() public view override returns (uint256) { if (totalDeposits == 0) return rewardPerTokenStored; uint256 timeElapsed = latestRewardsTimestamp() - lastAccountingTimestamp; uint256 rewardsForTime = timeElapsed * rewardRate; uint256 newRewardsPerToken = rewardsForTime * ONE / totalDepositsWithBoost; return rewardPerTokenStored + newRewardsPerToken; } /** * @notice Returns the number of stakes for a user. Can be used off-chain to * make iterating through user stakes easier. * * @param user The user to count stakes for. * * @return stakes The number of stakes for the user. */ function numStakes(address user) public view override returns (uint256) { return stakes[user].length; } // ============================================ HELPERS ============================================ /** * @dev Can only be called by the designated reward distributor */ modifier onlyRewardsDistribution() { if (!isRewardDistributor[msg.sender]) revert USR_NotDistributor(); _; } /** * @dev Update reward accounting for the global state totals. */ modifier updateRewards() { rewardPerTokenStored = rewardPerToken(); lastAccountingTimestamp = latestRewardsTimestamp(); _; } /** * @dev Blocks calls if contract is paused or killed. */ modifier whenNotPaused() { if (paused) revert STATE_ContractPaused(); if (ended) revert STATE_ContractKilled(); _; } /** * @dev Update reward for a specific user stake. */ function _updateRewardForStake(address user, uint256 depositId) internal { UserStake storage s = stakes[user][depositId]; if (s.amount == 0) return; uint256 earned = _earned(s); s.rewards += earned; s.rewardPerTokenPaid = rewardPerTokenStored; } /** * @dev Return how many rewards a stake has earned and has claimable. */ function _earned(UserStake memory s) internal view returns (uint256) { uint256 rewardPerTokenAcc = rewardPerTokenStored - s.rewardPerTokenPaid; uint256 newRewards = s.amountWithBoost * (rewardPerTokenAcc / ONE); return newRewards; } /** * @dev Maps Lock enum values to corresponding lengths of time and reward boosts. */ function _getBoost(Lock _lock) internal view returns (uint256 boost, uint256 timelock) { if (_lock == Lock.short) { return (SHORT_BOOST, SHORT_BOOST_TIME); } else if (_lock == Lock.medium) { return (MEDIUM_BOOST, MEDIUM_BOOST_TIME); } else if (_lock == Lock.long) { return (LONG_BOOST, LONG_BOOST_TIME); } else { revert USR_InvalidLockValue(uint256(_lock)); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; // ================================================================================================== // =========================== USER ERRORS ============================ // ================================================================================================== /// These errors represent invalid user input to functions. /// /// Where appropriate, the invalid value is specified along with constraints. /// /// These errors can be resolved by callers updating their arguments. /** * @notice User attempted to stake zero amout. */ error USR_ZeroDeposit(); /** * @notice User attempted to stake an amount smaller than the minimum deposit. * * @param amount Amount user attmpted to stake. * @param minimumDeposit The minimum deopsit amount accepted. */ error USR_MinimumDeposit(uint256 amount, uint256 minimumDeposit); /** * @notice The specified deposit ID does not exist for the caller. * * @param depositId The deposit ID provided for lookup. */ error USR_NoDeposit(uint256 depositId); /** * @notice The user is attempting to cancel unbonding for a deposit which is not unbonding. * * @param depositId The deposit ID the user attempted to cancel. */ error USR_NotUnbonding(uint256 depositId); /** * @notice The user is attempting to unbond a deposit which has already been unbonded. * * @param depositId The deposit ID the user attempted to unbond. */ error USR_AlreadyUnbonding(uint256 depositId); /** * @notice The user is attempting to unstake a deposit which is still timelocked. * * @param depositId The deposit ID the user attempted to unstake. */ error USR_StakeLocked(uint256 depositId); /** * @notice The contract owner attempted to update rewards but the new reward rate would cause overflow. */ error USR_RewardTooLarge(); /** * @notice The reward distributor attempted to update rewards but 0 rewards per epoch. * This can also happen if there is less than 1 wei of rewards per second of the * epoch - due to integer division this will also lead to 0 rewards. */ error USR_ZeroRewardsPerEpoch(); /** * @notice The caller attempted to stake with a lock value that did not * correspond to a valid staking time. * * @param lock The provided lock value. */ error USR_InvalidLockValue(uint256 lock); /** * @notice The caller attempted to call a reward distribution function, * but was not the designated distributor. * */ error USR_NotDistributor(); // ================================================================================================== // =========================== STATE ERRORS ============================ // ================================================================================================== /// These errors represent actions that are being prevented due to current contract state. /// /// These errors do not relate to user input, and may or may not be resolved by other actions /// or the progression of time. /** * @notice The caller attempted to change the epoch length, but current reward epochs were active. */ error STATE_RewardsOngoing(); /** * @notice The caller attempted to deposit stake, but there are no remaining rewards to pay out. */ error STATE_NoRewardsLeft(); /** * @notice The caller attempted to perform an an emergency unstake, but the contract * is not in emergency mode. */ error STATE_NoEmergencyUnstake(); /** * @notice The caller attempted to perform an an emergency unstake, but the contract * is not in emergency mode, or the emergency mode does not allow claiming rewards. */ error STATE_NoEmergencyClaim(); /** * @notice The owner attempted to place the contract in emergency mode, but emergency * mode was already enabled. */ error STATE_AlreadyStopped(); /** * @notice The caller attempted to perform a state-mutating action (e.g. staking or unstaking) * while the contract was paused. */ error STATE_ContractPaused(); /** * @notice The caller attempted to perform a state-mutating action (e.g. staking or unstaking) * while the contract was killed (placed in emergency mode). * @dev Emergency mode is irreversible. */ error STATE_ContractKilled(); // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title Sommelier Staking Interface * @author Kevin Kennis * * @notice Full documentation in implementation contract. */ interface ICellarStaking { // ===================== Events ======================= event Funding(uint256 rewardAmount, uint256 rewardEnd); event Stake(address indexed user, uint256 depositId, uint256 amount); event Unbond(address indexed user, uint256 depositId, uint256 amount); event CancelUnbond(address indexed user, uint256 depositId); event Unstake(address indexed user, uint256 depositId, uint256 amount, uint256 reward); event Claim(address indexed user, uint256 depositId, uint256 amount); event EmergencyStop(address owner, bool claimable); event EmergencyUnstake(address indexed user, uint256 depositId, uint256 amount); event EmergencyClaim(address indexed user, uint256 amount); event EpochDurationChange(uint256 duration); event DistributorSet(address indexed distributor, bool isSet); // ===================== Structs ====================== enum Lock { short, medium, long } struct UserStake { uint256 amount; uint256 amountWithBoost; uint256 rewardPerTokenPaid; uint256 rewards; uint256 unbondTimestamp; Lock lock; } // ============== Public State Variables ============== function stakingToken() external returns (ERC20); function distributionToken() external returns (ERC20); function epochDuration() external returns (uint256); function minimumDeposit() external returns (uint256); function endTimestamp() external returns (uint256); function totalDeposits() external returns (uint256); function totalDepositsWithBoost() external returns (uint256); function rewardRate() external returns (uint256); function rewardPerTokenStored() external returns (uint256); function paused() external returns (bool); function ended() external returns (bool); function claimable() external returns (bool); function isRewardDistributor(address user) external returns (bool); // ================ User Functions ================ function stake(uint256 amount, Lock lock) external; function unbond(uint256 depositId) external; function unbondAll() external; function cancelUnbonding(uint256 depositId) external; function cancelUnbondingAll() external; function unstake(uint256 depositId) external returns (uint256 reward); function unstakeAll() external returns (uint256[] memory rewards); function claim(uint256 depositId) external returns (uint256 reward); function claimAll() external returns (uint256[] memory rewards); function emergencyUnstake() external; function emergencyClaim() external; // ================ Admin Functions ================ function notifyRewardAmount(uint256 reward) external; function setRewardsDuration(uint256 _epochDuration) external; function setRewardsDistribution(address _rewardsDistribution, bool _set) external; function setMinimumDeposit(uint256 _minimum) external; function setPaused(bool _paused) external; function emergencyStop(bool makeRewardsClaimable) external; // ================ View Functions ================ function latestRewardsTimestamp() external view returns (uint256); function rewardPerToken() external view returns (uint256); function numStakes(address user) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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; 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"); (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"); (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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @notice Unstake a specific deposited stake. @dev The unbonding time for the specified deposit must have elapsed. @dev Unstaking automatically claims available rewards for the deposit. @param depositId The specified deposit to unstake from. @return reward The amount of accumulated rewards since the last reward claim./
function unstake(uint256 depositId) external override whenNotPaused updateRewards returns (uint256 reward) { return _unstake(depositId); }
535,325
[ 1, 984, 334, 911, 279, 2923, 443, 1724, 329, 384, 911, 18, 1377, 1021, 640, 26425, 310, 813, 364, 326, 1269, 443, 1724, 1297, 1240, 9613, 18, 1377, 1351, 334, 6159, 6635, 11955, 2319, 283, 6397, 364, 326, 443, 1724, 18, 225, 443, 1724, 548, 2398, 1021, 1269, 443, 1724, 358, 640, 334, 911, 628, 18, 327, 19890, 9079, 1021, 3844, 434, 24893, 283, 6397, 3241, 326, 1142, 19890, 7516, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 334, 911, 12, 11890, 5034, 443, 1724, 548, 13, 3903, 3849, 1347, 1248, 28590, 1089, 17631, 14727, 1135, 261, 11890, 5034, 19890, 13, 288, 203, 3639, 327, 389, 23412, 911, 12, 323, 1724, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xB3d7bbEf0D9bF76dd46e3b9227446EfBa9231833/sources/src/main/solidity/DVP.sol
* @dev Get the list of price oracles for a given token. @param tokenAddress Token address. @return List of addresses of all the price oracles for a given token./
function priceOracles(address tokenAddress) external view returns (address[] memory) { return _priceOracles[tokenAddress]; }
4,790,570
[ 1, 967, 326, 666, 434, 6205, 578, 69, 9558, 364, 279, 864, 1147, 18, 225, 1147, 1887, 3155, 1758, 18, 327, 987, 434, 6138, 434, 777, 326, 6205, 578, 69, 9558, 364, 279, 864, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6205, 51, 354, 9558, 12, 2867, 1147, 1887, 13, 3903, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 389, 8694, 51, 354, 9558, 63, 2316, 1887, 15533, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsStable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } pragma solidity ^0.6.0; interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.6.0; library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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); } } } } pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } pragma solidity ^0.6.0; abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } pragma solidity ^0.6.0; contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } pragma solidity ^0.6.0; abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable burnGas(20) { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } pragma solidity ^0.6.0; import "./Gem.sol"; abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } pragma solidity ^0.6.0; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } pragma solidity ^0.6.0; contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } pragma solidity ^0.6.0; interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); function borrowCaps(address) external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; import "./CarefulMath.sol"; contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } } pragma solidity ^0.6.0; contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProviderV2 { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } interface ILendingPoolV2 { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; ManagerType managerType; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } pragma solidity ^0.6.0; abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } pragma solidity ^0.6.0; /// @title Implements enum Method abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } pragma solidity ^0.6.0; abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr) ); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _proxy.transfer(address(this).balance); } } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, DFSExchangeData.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } pragma solidity ^0.6.0; abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; contract DFSPrices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; ManagerType managerType; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee); (, daiSwaped) = _buy(_exchangeData); } address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve DSProxy to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { (address cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface( 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B ); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: comp.compSupplierIndex(_cToken, _supplier) }); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: comp.compBorrowerIndex(_cToken, _borrower) }); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.user = msg.sender; exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; uint borrowCap; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]), borrowCap: comp.borrowCaps(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1500000; uint public BOOST_GAS_COST = 1000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(user); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_market, _users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); uint256 globalBorrowAmount = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; uint256 borrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); }
@dev Called by the DSProxy contract which owns the CDP @notice Adds the users CDP in the list of subscriptions so it can be monitored @param _cdpId Id of the CDP @param _minRatio Minimum ratio below which repay is triggered @param _maxRatio Maximum ratio after which boost is triggered @param _optimalBoost Ratio amount which boost should target @param _optimalRepay Ratio amount which repay should target @param _boostEnabled Boolean determing if boost is enabled @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp if boost is not enabled, set max ratio to max uint
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } }
380,587
[ 1, 8185, 635, 326, 8678, 3886, 6835, 1492, 29065, 326, 385, 8640, 225, 15605, 326, 3677, 385, 8640, 316, 326, 666, 434, 11912, 1427, 518, 848, 506, 28651, 225, 389, 4315, 84, 548, 3124, 434, 326, 385, 8640, 225, 389, 1154, 8541, 23456, 7169, 5712, 1492, 2071, 528, 353, 10861, 225, 389, 1896, 8541, 18848, 7169, 1839, 1492, 14994, 353, 10861, 225, 389, 3838, 2840, 26653, 534, 4197, 3844, 1492, 14994, 1410, 1018, 225, 389, 3838, 2840, 426, 10239, 534, 4197, 3844, 1492, 2071, 528, 1410, 1018, 225, 389, 25018, 1526, 3411, 302, 847, 11987, 309, 14994, 353, 3696, 225, 389, 4285, 5147, 1526, 3411, 302, 847, 11987, 309, 732, 848, 999, 1024, 5147, 364, 333, 7976, 84, 309, 14994, 353, 486, 3696, 16, 444, 943, 7169, 358, 943, 2254, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9129, 12, 11890, 389, 4315, 84, 548, 16, 2254, 10392, 389, 1154, 8541, 16, 2254, 10392, 389, 1896, 8541, 16, 2254, 10392, 389, 3838, 2840, 26653, 16, 2254, 10392, 389, 3838, 2840, 426, 10239, 16, 1426, 389, 25018, 1526, 16, 1426, 389, 4285, 5147, 1526, 13, 3903, 288, 203, 3639, 2583, 12, 291, 5541, 12, 3576, 18, 15330, 16, 389, 4315, 84, 548, 3631, 315, 10136, 506, 2566, 635, 385, 9295, 3410, 8863, 203, 203, 3639, 2254, 10392, 1191, 2747, 8541, 273, 389, 25018, 1526, 692, 389, 1896, 8541, 294, 2254, 10392, 19236, 21, 1769, 203, 3639, 2583, 12, 1893, 1370, 12, 4181, 18, 330, 7904, 24899, 4315, 84, 548, 3631, 389, 1154, 8541, 16, 1191, 2747, 8541, 3631, 315, 10136, 506, 3434, 859, 8863, 203, 203, 3639, 2592, 2555, 2502, 720, 966, 273, 16768, 1616, 63, 67, 4315, 84, 548, 15533, 203, 203, 3639, 385, 9295, 6064, 3778, 4915, 273, 385, 9295, 6064, 12590, 203, 7734, 1131, 8541, 30, 389, 1154, 8541, 16, 203, 7734, 943, 8541, 30, 1191, 2747, 8541, 16, 203, 7734, 16413, 8541, 26653, 30, 389, 3838, 2840, 26653, 16, 203, 7734, 16413, 8541, 426, 10239, 30, 389, 3838, 2840, 426, 10239, 16, 203, 7734, 3410, 30, 1234, 18, 15330, 16, 203, 7734, 7976, 84, 548, 30, 389, 4315, 84, 548, 16, 203, 7734, 14994, 1526, 30, 389, 25018, 1526, 16, 203, 7734, 1024, 5147, 1526, 30, 389, 4285, 5147, 1526, 203, 5411, 15549, 203, 203, 3639, 2549, 1016, 9904, 31, 203, 203, 3639, 309, 261, 1717, 966, 2 ]
./full_match/1/0x70996FeE3bc1BA38e36Ea356aee5d855161e6e52/sources/contracts/ChainPortal.sol
* @notice Executes the next pending action in the queue, skipping aborted actions. @dev If there is no pending action queued, the function will revert. @dev The first pending action that is not aborted will be executed./
function _executeAction(uint64 sourceChainSelector, CrossChainAction memory action) private { bool success; bytes memory callData; bytes memory resultData; _verifyActionRestrictions(action.sender, action.targets, sourceChainSelector); for (uint256 i; i < action.targets.length;) { if(bytes(action.signatures[i]).length == 0) { callData = action.calldatas[i]; callData = abi.encodePacked(bytes4(keccak256(bytes(action.signatures[i]))), action.calldatas[i]); } if (!success) { if (resultData.length > 0) { assembly { let size := mload(resultData) revert(add(32, resultData), size) } revert ChainPortal__ActionExecutionFailed(); } } unchecked { ++i; } } }
16,577,505
[ 1, 9763, 326, 1024, 4634, 1301, 316, 326, 2389, 16, 14195, 18166, 4209, 18, 225, 971, 1915, 353, 1158, 4634, 1301, 12234, 16, 326, 445, 903, 15226, 18, 225, 1021, 1122, 4634, 1301, 716, 353, 486, 18166, 903, 506, 7120, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8837, 1803, 12, 11890, 1105, 1084, 3893, 4320, 16, 19742, 3893, 1803, 3778, 1301, 13, 3238, 288, 203, 3639, 1426, 2216, 31, 203, 3639, 1731, 3778, 745, 751, 31, 203, 3639, 1731, 3778, 563, 751, 31, 203, 3639, 389, 8705, 1803, 26175, 12, 1128, 18, 15330, 16, 1301, 18, 11358, 16, 1084, 3893, 4320, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 1301, 18, 11358, 18, 2469, 30943, 288, 203, 5411, 309, 12, 3890, 12, 1128, 18, 30730, 63, 77, 65, 2934, 2469, 422, 374, 13, 288, 203, 7734, 745, 751, 273, 1301, 18, 1991, 13178, 63, 77, 15533, 203, 7734, 745, 751, 273, 24126, 18, 3015, 4420, 329, 12, 3890, 24, 12, 79, 24410, 581, 5034, 12, 3890, 12, 1128, 18, 30730, 63, 77, 22643, 3631, 1301, 18, 1991, 13178, 63, 77, 19226, 203, 5411, 289, 203, 5411, 309, 16051, 4768, 13, 288, 203, 7734, 309, 261, 2088, 751, 18, 2469, 405, 374, 13, 288, 203, 10792, 19931, 288, 203, 13491, 2231, 963, 519, 312, 945, 12, 2088, 751, 13, 203, 13491, 15226, 12, 1289, 12, 1578, 16, 563, 751, 3631, 963, 13, 203, 10792, 289, 203, 10792, 15226, 7824, 24395, 972, 1803, 3210, 2925, 5621, 203, 7734, 289, 203, 5411, 289, 203, 5411, 22893, 288, 203, 7734, 965, 77, 31, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title Module * @dev Interface for a module. * A module MUST implement the addModule() method to ensure that a wallet with at least one module * can never end up in a "frozen" state. * @author Julien Niset - <[email protected]> */ interface Module { /** * @dev Inits a module for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external; /** * @dev Adds a module to a wallet. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external; /** * @dev Utility method to recover any ERC20 token that was sent to the * module by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; } /** * @title BaseModule * @dev Basic module that contains some methods common to all modules. * @author Julien Niset - <[email protected]> */ contract BaseModule is Module { // The adddress of the module registry. ModuleRegistry internal registry; event ModuleCreated(bytes32 name); event ModuleInitialised(address wallet); constructor(ModuleRegistry _registry, bytes32 _name) public { registry = _registry; emit ModuleCreated(_name); } /** * @dev Throws if the sender is not the target wallet of the call. */ modifier onlyWallet(BaseWallet _wallet) { require(msg.sender == address(_wallet), "BM: caller must be wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet or the module itself. */ modifier onlyOwner(BaseWallet _wallet) { require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet. */ modifier strictOnlyOwner(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet"); _; } /** * @dev Inits the module for a wallet by logging an event. * The method can only be called by the wallet itself. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { emit ModuleInitialised(_wallet); } /** * @dev Adds a module to a wallet. First checks that the module is registered. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external strictOnlyOwner(_wallet) { require(registry.isRegisteredModule(_module), "BM: module is not registered"); _wallet.authoriseModule(_module, true); } /** * @dev Utility method enbaling anyone to recover ERC20 token sent to the * module by mistake and transfer them to the Module Registry. * @param _token The token to recover. */ function recoverToken(address _token) external { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(address(registry), total); } /** * @dev Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) { return _wallet.owner() == _addr; } } /** * @title RelayerModule * @dev Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer. * @author Julien Niset - <[email protected]> */ contract RelayerModule is Module { uint256 constant internal BLOCKBOUND = 10000; mapping (address => RelayerConfig) public relayer; struct RelayerConfig { uint256 nonce; mapping (bytes32 => bool) executedTx; } event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash); /** * @dev Throws if the call did not go through the execute() method. */ modifier onlyExecute { require(msg.sender == address(this), "RM: must be called via execute()"); _; } /* ***************** Abstract method ************************* */ /** * @dev Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures. */ function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256); /** * @dev Validates the signatures provided with a relayed transaction. * The method MUST throw if one or more signatures are not valid. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @param _signHash The signed hash representing the relayed transaction. * @param _signatures The signatures as a concatenated byte array. */ function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool); /* ************************************************************ */ /** * @dev Executes a relayed transaction. * @param _wallet The target wallet. * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _signatures The signatures as a concatenated byte array. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function execute( BaseWallet _wallet, bytes _data, uint256 _nonce, bytes _signatures, uint256 _gasPrice, uint256 _gasLimit ) external returns (bool success) { uint startGas = gasleft(); bytes32 signHash = getSignHash(address(this), _wallet, 0, _data, _nonce, _gasPrice, _gasLimit); require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request"); require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data"); uint256 requiredSignatures = getRequiredSignatures(_wallet, _data); if((requiredSignatures * 65) == _signatures.length) { if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) { if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) { // solium-disable-next-line security/no-call-value success = address(this).call(_data); refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender); } } } emit TransactionExecuted(_wallet, success, signHash); } /** * @dev Gets the current nonce for a wallet. * @param _wallet The target wallet. */ function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) { return relayer[_wallet].nonce; } /** * @dev Generates the signed hash of a relayed transaction according to ERC 1077. * @param _from The starting address for the relayed transaction (should be the module) * @param _to The destination address for the relayed transaction (should be the wallet) * @param _value The value for the relayed transaction * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function getSignHash( address _from, address _to, uint256 _value, bytes _data, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit)) )); } /** * @dev Checks if the relayed transaction is unique. * @param _wallet The target wallet. * @param _nonce The nonce * @param _signHash The signed hash of the transaction */ function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { if(relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } /** * @dev Checks that a nonce has the correct format and is valid. * It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if(_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if(nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; } /** * @dev Recovers the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); return ecrecover(_signedHash, v, r, s); } /** * @dev Refunds the gas used to the Relayer. * For security reasons the default behavior is to not refund calls with 0 or 1 signatures. * @param _wallet The target wallet. * @param _gasUsed The gas used. * @param _gasPrice The gas price for the refund. * @param _gasLimit The gas limit for the refund. * @param _signatures The number of signatures used in the call. * @param _relayer The address of the Relayer. */ function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed // only refund if gas price not null, more than 1 signatures, gas less than gasLimit if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } _wallet.invoke(_relayer, amount, ""); } } /** * @dev Returns false if the refund is expected to fail. * @param _wallet The target wallet. * @param _gasUsed The expected gas used. * @param _gasPrice The expected gas price for the refund. */ function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 1 && (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(this) == false)) { return false; } return true; } /** * @dev Checks that the wallet address provided as the first parameter of the relayed data is the same * as the wallet passed as the input of the execute() method. @return false if the addresses are different. */ function verifyData(address _wallet, bytes _data) private pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet; // solium-disable-next-line security/no-inline-assembly assembly { //_data = {length:32}{sig:4}{_wallet:32}{...} dataWallet := mload(add(_data, 0x24)) } return dataWallet == _wallet; } /** * @dev Parses the data to extract the method signature. */ function functionPrefix(bytes _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solium-disable-next-line security/no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } } /** * @title LimitManager * @dev Module to transfer tokens (ETH or ERC20) based on a security context (daily limit, whitelist, etc). * @author Julien Niset - <[email protected]> */ contract LimitManager is BaseModule { // large limit when the limit can be considered disabled uint128 constant internal LIMIT_DISABLED = uint128(-1); // 3.40282366920938463463374607431768211455e+38 using SafeMath for uint256; struct LimitManagerConfig { // The global limit Limit limit; // whitelist DailySpent dailySpent; } struct Limit { // the current limit uint128 current; // the pending limit if any uint128 pending; // when the pending limit becomes the current limit uint64 changeAfter; } struct DailySpent { // The amount already spent during the current period uint128 alreadySpent; // The end of the current period uint64 periodEnd; } // wallet specific storage mapping (address => LimitManagerConfig) internal limits; // The default limit uint256 public defaultLimit; // *************** Events *************************** // event LimitChanged(address indexed wallet, uint indexed newLimit, uint64 indexed startAfter); // *************** Constructor ********************** // constructor(uint256 _defaultLimit) public { defaultLimit = _defaultLimit; } // *************** External/Public Functions ********************* // /** * @dev Inits the module for a wallet by setting the limit to the default value. * @param _wallet The target wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { Limit storage limit = limits[_wallet].limit; if(limit.current == 0 && limit.changeAfter == 0) { limit.current = uint128(defaultLimit); } } /** * @dev Changes the global limit. * The limit is expressed in ETH and the change is pending for the security period. * @param _wallet The target wallet. * @param _newLimit The new limit. * @param _securityPeriod The security period. */ function changeLimit(BaseWallet _wallet, uint256 _newLimit, uint256 _securityPeriod) internal { Limit storage limit = limits[_wallet].limit; // solium-disable-next-line security/no-block-members uint128 currentLimit = (limit.changeAfter > 0 && limit.changeAfter < now) ? limit.pending : limit.current; limit.current = currentLimit; limit.pending = uint128(_newLimit); // solium-disable-next-line security/no-block-members limit.changeAfter = uint64(now.add(_securityPeriod)); // solium-disable-next-line security/no-block-members emit LimitChanged(_wallet, _newLimit, uint64(now.add(_securityPeriod))); } // *************** Internal Functions ********************* // /** * @dev Gets the current global limit for a wallet. * @param _wallet The target wallet. * @return the current limit expressed in ETH. */ function getCurrentLimit(BaseWallet _wallet) public view returns (uint256 _currentLimit) { Limit storage limit = limits[_wallet].limit; _currentLimit = uint256(currentLimit(limit.current, limit.pending, limit.changeAfter)); } /** * @dev Gets a pending limit for a wallet if any. * @param _wallet The target wallet. * @return the pending limit (in ETH) and the time at chich it will become effective. */ function getPendingLimit(BaseWallet _wallet) external view returns (uint256 _pendingLimit, uint64 _changeAfter) { Limit storage limit = limits[_wallet].limit; // solium-disable-next-line security/no-block-members return ((now < limit.changeAfter)? (uint256(limit.pending), limit.changeAfter) : (0,0)); } /** * @dev Gets the amount of tokens that has not yet been spent during the current period. * @param _wallet The target wallet. * @return the amount of tokens (in ETH) that has not been spent yet and the end of the period. */ function getDailyUnspent(BaseWallet _wallet) external view returns (uint256 _unspent, uint64 _periodEnd) { uint256 globalLimit = getCurrentLimit(_wallet); DailySpent storage expense = limits[_wallet].dailySpent; // solium-disable-next-line security/no-block-members if(now > expense.periodEnd) { _unspent = globalLimit; _periodEnd = uint64(now + 24 hours); } else { _unspent = globalLimit - expense.alreadySpent; _periodEnd = expense.periodEnd; } } /** * @dev Helper method to check if a transfer is within the limit. * If yes the daily unspent for the current period is updated. * @param _wallet The target wallet. * @param _amount The amount for the transfer */ function checkAndUpdateDailySpent(BaseWallet _wallet, uint _amount) internal returns (bool) { Limit storage limit = limits[_wallet].limit; uint128 current = currentLimit(limit.current, limit.pending, limit.changeAfter); if(isWithinDailyLimit(_wallet, current, _amount)) { updateDailySpent(_wallet, current, _amount); return true; } return false; } /** * @dev Helper method to update the daily spent for the current period. * @param _wallet The target wallet. * @param _limit The current limit for the wallet. * @param _amount The amount to add to the daily spent. */ function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal { if(_limit != LIMIT_DISABLED) { DailySpent storage expense = limits[_wallet].dailySpent; if (expense.periodEnd < now) { expense.periodEnd = uint64(now + 24 hours); expense.alreadySpent = uint128(_amount); } else { expense.alreadySpent += uint128(_amount); } } } /** * @dev Checks if a transfer amount is withing the daily limit for a wallet. * @param _wallet The target wallet. * @param _limit The current limit for the wallet. * @param _amount The transfer amount. * @return true if the transfer amount is withing the daily limit. */ function isWithinDailyLimit(BaseWallet _wallet, uint _limit, uint _amount) internal view returns (bool) { DailySpent storage expense = limits[_wallet].dailySpent; if(_limit == LIMIT_DISABLED) { return true; } else if (expense.periodEnd < now) { return (_amount <= _limit); } else { return (expense.alreadySpent + _amount <= _limit && expense.alreadySpent + _amount >= expense.alreadySpent); } } /** * @dev Helper method to get the current limit from a Limit struct. * @param _current The value of the current parameter * @param _pending The value of the pending parameter * @param _changeAfter The value of the changeAfter parameter */ function currentLimit(uint128 _current, uint128 _pending, uint64 _changeAfter) internal view returns (uint128) { if(_changeAfter > 0 && _changeAfter < now) { return _pending; } return _current; } } /** * ERC20 contract interface. */ contract ERC20 { function totalSupply() public view returns (uint); function decimals() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); } /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } /** * @dev Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; if(a % b == 0) { return c; } else { return c + 1; } } } /** * @title Owned * @dev Basic contract to define an owner. * @author Julien Niset - <[email protected]> */ contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @dev Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @dev Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Address must not be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } } /** * @title ModuleRegistry * @dev Registry of authorised modules. * Modules must be registered before they can be authorised on a wallet. * @author Julien Niset - <[email protected]> */ contract ModuleRegistry is Owned { mapping (address => Info) internal modules; mapping (address => Info) internal upgraders; event ModuleRegistered(address indexed module, bytes32 name); event ModuleDeRegistered(address module); event UpgraderRegistered(address indexed upgrader, bytes32 name); event UpgraderDeRegistered(address upgrader); struct Info { bool exists; bytes32 name; } /** * @dev Registers a module. * @param _module The module. * @param _name The unique name of the module. */ function registerModule(address _module, bytes32 _name) external onlyOwner { require(!modules[_module].exists, "MR: module already exists"); modules[_module] = Info({exists: true, name: _name}); emit ModuleRegistered(_module, _name); } /** * @dev Deregisters a module. * @param _module The module. */ function deregisterModule(address _module) external onlyOwner { require(modules[_module].exists, "MR: module does not exists"); delete modules[_module]; emit ModuleDeRegistered(_module); } /** * @dev Registers an upgrader. * @param _upgrader The upgrader. * @param _name The unique name of the upgrader. */ function registerUpgrader(address _upgrader, bytes32 _name) external onlyOwner { require(!upgraders[_upgrader].exists, "MR: upgrader already exists"); upgraders[_upgrader] = Info({exists: true, name: _name}); emit UpgraderRegistered(_upgrader, _name); } /** * @dev Deregisters an upgrader. * @param _upgrader The _upgrader. */ function deregisterUpgrader(address _upgrader) external onlyOwner { require(upgraders[_upgrader].exists, "MR: upgrader does not exists"); delete upgraders[_upgrader]; emit UpgraderDeRegistered(_upgrader); } /** * @dev Utility method enbaling the owner of the registry to claim any ERC20 token that was sent to the * registry. * @param _token The token to recover. */ function recoverToken(address _token) external onlyOwner { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, total); } /** * @dev Gets the name of a module from its address. * @param _module The module address. * @return the name. */ function moduleInfo(address _module) external view returns (bytes32) { return modules[_module].name; } /** * @dev Gets the name of an upgrader from its address. * @param _upgrader The upgrader address. * @return the name. */ function upgraderInfo(address _upgrader) external view returns (bytes32) { return upgraders[_upgrader].name; } /** * @dev Checks if a module is registered. * @param _module The module address. * @return true if the module is registered. */ function isRegisteredModule(address _module) external view returns (bool) { return modules[_module].exists; } /** * @dev Checks if a list of modules are registered. * @param _modules The list of modules address. * @return true if all the modules are registered. */ function isRegisteredModule(address[] _modules) external view returns (bool) { for(uint i = 0; i < _modules.length; i++) { if (!modules[_modules[i]].exists) { return false; } } return true; } /** * @dev Checks if an upgrader is registered. * @param _upgrader The upgrader address. * @return true if the upgrader is registered. */ function isRegisteredUpgrader(address _upgrader) external view returns (bool) { return upgraders[_upgrader].exists; } } /** * @title BaseWallet * @dev Simple modular wallet that authorises modules to call its invoke() method. * Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by * @author Julien Niset - <[email protected]> */ contract BaseWallet { // The implementation of the proxy address public implementation; // The owner address public owner; // The authorised modules mapping (address => bool) public authorised; // The enabled static calls mapping (bytes4 => address) public enabled; // The number of modules uint public modules; event AuthorisedModule(address indexed module, bool value); event EnabledStaticCall(address indexed module, bytes4 indexed method); event Invoked(address indexed module, address indexed target, uint indexed value, bytes data); event Received(uint indexed value, address indexed sender, bytes data); event OwnerChanged(address owner); /** * @dev Throws if the sender is not an authorised module. */ modifier moduleOnly { require(authorised[msg.sender], "BW: msg.sender not an authorized module"); _; } /** * @dev Inits the wallet by setting the owner and authorising a list of modules. * @param _owner The owner. * @param _modules The modules to authorise. */ function init(address _owner, address[] _modules) external { require(owner == address(0) && modules == 0, "BW: wallet already initialised"); require(_modules.length > 0, "BW: construction requires at least 1 module"); owner = _owner; modules = _modules.length; for(uint256 i = 0; i < _modules.length; i++) { require(authorised[_modules[i]] == false, "BW: module is already added"); authorised[_modules[i]] = true; Module(_modules[i]).init(this); emit AuthorisedModule(_modules[i], true); } } /** * @dev Enables/Disables a module. * @param _module The target module. * @param _value Set to true to authorise the module. */ function authoriseModule(address _module, bool _value) external moduleOnly { if (authorised[_module] != _value) { if(_value == true) { modules += 1; authorised[_module] = true; Module(_module).init(this); } else { modules -= 1; require(modules > 0, "BW: wallet must have at least one module"); delete authorised[_module]; } emit AuthorisedModule(_module, _value); } } /** * @dev Enables a static method by specifying the target module to which the call * must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external moduleOnly { require(authorised[_module], "BW: must be an authorised module for static call"); enabled[_method] = _module; emit EnabledStaticCall(_module, _method); } /** * @dev Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @dev Performs a generic transaction. * @param _target The address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invoke(address _target, uint _value, bytes _data) external moduleOnly { // solium-disable-next-line security/no-call-value require(_target.call.value(_value)(_data), "BW: call to target failed"); emit Invoked(msg.sender, _target, _value, _data); } /** * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to * implement specific static methods. It delegates the static call to a target contract if the data corresponds * to an enabled method, or logs the call otherwise. */ function() public payable { if(msg.data.length > 0) { address module = enabled[msg.sig]; if(module == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require(authorised[module], "BW: must be an authorised module for static call"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, module, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } } } contract TokenPriceProvider { using SafeMath for uint256; // Mock token address for ETH address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Address of Kyber's trading contract address constant internal KYBER_NETWORK_ADDRESS = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755; mapping(address => uint256) public cachedPrices; function syncPrice(ERC20 token) public { uint256 expectedRate; (expectedRate,) = kyberNetwork().getExpectedRate(token, ERC20(ETH_TOKEN_ADDRESS), 10000); cachedPrices[token] = expectedRate; } // // Convenience functions // function syncPriceForTokenList(ERC20[] tokens) public { for(uint16 i = 0; i < tokens.length; i++) { syncPrice(tokens[i]); } } /** * @dev Converts the value of _amount tokens in ether. * @param _amount the amount of tokens to convert (in 'token wei' twei) * @param _token the ERC20 token contract * @return the ether value (in wei) of _amount tokens with contract _token */ function getEtherValue(uint256 _amount, address _token) public view returns (uint256) { uint256 decimals = ERC20(_token).decimals(); uint256 price = cachedPrices[_token]; return price.mul(_amount).div(10**decimals); } // // Internal // function kyberNetwork() internal view returns (KyberNetwork) { return KyberNetwork(KYBER_NETWORK_ADDRESS); } } contract KyberNetwork { function getExpectedRate( ERC20 src, ERC20 dest, uint srcQty ) public view returns (uint expectedRate, uint slippageRate); function trade( ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint); } /** * @title Storage * @dev Base contract for the storage of a wallet. * @author Julien Niset - <[email protected]> */ contract Storage { /** * @dev Throws if the caller is not an authorised module. */ modifier onlyModule(BaseWallet _wallet) { require(_wallet.authorised(msg.sender), "TS: must be an authorized module to call this method"); _; } } /** * @title GuardianStorage * @dev Contract storing the state of wallets related to guardians and lock. * The contract only defines basic setters and getters with no logic. Only modules authorised * for a wallet can modify its state. * @author Julien Niset - <[email protected]> * @author Olivier Van Den Biggelaar - <[email protected]> */ contract GuardianStorage is Storage { struct GuardianStorageConfig { // the list of guardians address[] guardians; // the info about guardians mapping (address => GuardianInfo) info; // the lock's release timestamp uint256 lock; // the module that set the last lock address locker; } struct GuardianInfo { bool exists; uint128 index; } // wallet specific storage mapping (address => GuardianStorageConfig) internal configs; // *************** External Functions ********************* // /** * @dev Lets an authorised module add a guardian to a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(BaseWallet _wallet, address _guardian) external onlyModule(_wallet) { GuardianStorageConfig storage config = configs[_wallet]; config.info[_guardian].exists = true; config.info[_guardian].index = uint128(config.guardians.push(_guardian) - 1); } /** * @dev Lets an authorised module revoke a guardian from a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(BaseWallet _wallet, address _guardian) external onlyModule(_wallet) { GuardianStorageConfig storage config = configs[_wallet]; address lastGuardian = config.guardians[config.guardians.length - 1]; if (_guardian != lastGuardian) { uint128 targetIndex = config.info[_guardian].index; config.guardians[targetIndex] = lastGuardian; config.info[lastGuardian].index = targetIndex; } config.guardians.length--; delete config.info[_guardian]; } /** * @dev Returns the number of guardians for a wallet. * @param _wallet The target wallet. * @return the number of guardians. */ function guardianCount(BaseWallet _wallet) external view returns (uint256) { return configs[_wallet].guardians.length; } /** * @dev Gets the list of guaridans for a wallet. * @param _wallet The target wallet. * @return the list of guardians. */ function getGuardians(BaseWallet _wallet) external view returns (address[]) { GuardianStorageConfig storage config = configs[_wallet]; address[] memory guardians = new address[](config.guardians.length); for (uint256 i = 0; i < config.guardians.length; i++) { guardians[i] = config.guardians[i]; } return guardians; } /** * @dev Checks if an account is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The account. * @return true if the account is a guardian for a wallet. */ function isGuardian(BaseWallet _wallet, address _guardian) external view returns (bool) { return configs[_wallet].info[_guardian].exists; } /** * @dev Lets an authorised module set the lock for a wallet. * @param _wallet The target wallet. * @param _releaseAfter The epoch time at which the lock should automatically release. */ function setLock(BaseWallet _wallet, uint256 _releaseAfter) external onlyModule(_wallet) { configs[_wallet].lock = _releaseAfter; if(_releaseAfter != 0 && msg.sender != configs[_wallet].locker) { configs[_wallet].locker = msg.sender; } } /** * @dev Checks if the lock is set for a wallet. * @param _wallet The target wallet. * @return true if the lock is set for the wallet. */ function isLocked(BaseWallet _wallet) external view returns (bool) { return configs[_wallet].lock > now; } /** * @dev Gets the time at which the lock of a wallet will release. * @param _wallet The target wallet. * @return the time at which the lock of a wallet will release, or zero if there is no lock set. */ function getLock(BaseWallet _wallet) external view returns (uint256) { return configs[_wallet].lock; } /** * @dev Gets the address of the last module that modified the lock for a wallet. * @param _wallet The target wallet. * @return the address of the last module that modified the lock for a wallet. */ function getLocker(BaseWallet _wallet) external view returns (address) { return configs[_wallet].locker; } } /** * @title TransferStorage * @dev Contract storing the state of wallets related to transfers (limit and whitelist). * The contract only defines basic setters and getters with no logic. Only modules authorised * for a wallet can modify its state. * @author Julien Niset - <[email protected]> */ contract TransferStorage is Storage { // wallet specific storage mapping (address => mapping (address => uint256)) internal whitelist; // *************** External Functions ********************* // /** * @dev Lets an authorised module add or remove an account from the whitelist of a wallet. * @param _wallet The target wallet. * @param _target The account to add/remove. * @param _value True for addition, false for revokation. */ function setWhitelist(BaseWallet _wallet, address _target, uint256 _value) external onlyModule(_wallet) { whitelist[_wallet][_target] = _value; } /** * @dev Gets the whitelist state of an account for a wallet. * @param _wallet The target wallet. * @param _target The account. * @return the epoch time at which an account strats to be whitelisted, or zero if the account is not whitelisted. */ function getWhitelist(BaseWallet _wallet, address _target) external view returns (uint256) { return whitelist[_wallet][_target]; } } /** * @title TokenTransfer * @dev Module to transfer tokens (ETH or ERC20) based on a security context (daily limit, whitelist, etc). * @author Julien Niset - <[email protected]> */ contract TokenTransfer is BaseModule, RelayerModule, LimitManager { bytes32 constant NAME = "TokenTransfer"; bytes4 constant internal EXECUTE_PENDING_PREFIX = bytes4(keccak256("executePendingTransfer(address,address,address,uint256,bytes,uint256)")); bytes constant internal EMPTY_BYTES = ""; using SafeMath for uint256; // Mock token address for ETH address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // large limit when the limit can be considered disabled uint128 constant internal LIMIT_DISABLED = uint128(-1); // 3.40282366920938463463374607431768211455e+38 struct TokenTransferConfig { // Mapping between pending transfer hash and their timestamp mapping (bytes32 => uint256) pendingTransfers; } // wallet specific storage mapping (address => TokenTransferConfig) internal configs; // The security period uint256 public securityPeriod; // The execution window uint256 public securityWindow; // The Guardian storage GuardianStorage public guardianStorage; // The Token storage TransferStorage public transferStorage; // The Token price provider TokenPriceProvider public priceProvider; // *************** Events *************************** // event Transfer(address indexed wallet, address indexed token, uint256 indexed amount, address to, bytes data); event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter); event RemovedFromWhitelist(address indexed wallet, address indexed target); event PendingTransferCreated(address indexed wallet, bytes32 indexed id, uint256 indexed executeAfter, address token, address to, uint256 amount, bytes data); event PendingTransferExecuted(address indexed wallet, bytes32 indexed id); event PendingTransferCanceled(address indexed wallet, bytes32 indexed id); // *************** Modifiers *************************** // /** * @dev Throws if the caller is not the owner or an authorised module. */ modifier onlyOwnerOrModule(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender) || _wallet.authorised(msg.sender), "TT: must be wallet owner or module"); _; } /** * @dev Throws if the wallet is locked. */ modifier onlyWhenUnlocked(BaseWallet _wallet) { // solium-disable-next-line security/no-block-members require(!guardianStorage.isLocked(_wallet), "TT: wallet must be unlocked"); _; } // *************** Constructor ********************** // constructor( ModuleRegistry _registry, TransferStorage _transferStorage, GuardianStorage _guardianStorage, address _priceProvider, uint256 _securityPeriod, uint256 _securityWindow, uint256 _defaultLimit ) BaseModule(_registry, NAME) LimitManager(_defaultLimit) public { transferStorage = _transferStorage; guardianStorage = _guardianStorage; priceProvider = TokenPriceProvider(_priceProvider); securityPeriod = _securityPeriod; securityWindow = _securityWindow; } // *************** External/Public Functions ********************* // /** * @dev lets the owner transfer tokens (ETH or ERC20) from a wallet. * @param _wallet The target wallet. * @param _token The address of the token to transfer. * @param _to The destination address * @param _amount The amoutn of token to transfer * @param _data The data for the transaction */ function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { // eth transfer to whitelist if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } // erc20 transfer to whitelist else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { // eth transfer under the limit if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } // eth transfer above the limit else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); // erc20 transfer under the limit if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } // erc20 transfer above the limit else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } /** * @dev Adds an address to the whitelist of a wallet. * @param _wallet The target wallet. * @param _target The address to add. */ function addToWhitelist( BaseWallet _wallet, address _target ) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(!isWhitelisted(_wallet, _target), "TT: target already whitelisted"); // solium-disable-next-line security/no-block-members uint256 whitelistAfter = now.add(securityPeriod); transferStorage.setWhitelist(_wallet, _target, whitelistAfter); emit AddedToWhitelist(_wallet, _target, uint64(whitelistAfter)); } /** * @dev Removes an address from the whitelist of a wallet. * @param _wallet The target wallet. * @param _target The address to remove. */ function removeFromWhitelist( BaseWallet _wallet, address _target ) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(isWhitelisted(_wallet, _target), "TT: target not whitelisted"); transferStorage.setWhitelist(_wallet, _target, 0); emit RemovedFromWhitelist(_wallet, _target); } /** * @dev Executes a pending transfer for a wallet. * The destination address is automatically added to the whitelist. * The method can be called by anyone to enable orchestration. * @param _wallet The target wallet. * @param _token The token of the pending transfer. * @param _to The destination address of the pending transfer. * @param _amount The amount of token to transfer of the pending transfer. * @param _block The block at which the pending transfer was created. */ function executePendingTransfer( BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data, uint _block ) public onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, _block)); uint executeAfter = configs[_wallet].pendingTransfers[id]; uint executeBefore = executeAfter.add(securityWindow); require(executeAfter <= now && now <= executeBefore, "TT: outside of the execution window"); removePendingTransfer(_wallet, id); if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } emit PendingTransferExecuted(_wallet, id); } /** * @dev Cancels a pending transfer for a wallet. * @param _wallet The target wallet. * @param _id the pending transfer Id. */ function cancelPendingTransfer( BaseWallet _wallet, bytes32 _id ) public onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(configs[_wallet].pendingTransfers[_id] > 0, "TT: unknown pending transfer"); removePendingTransfer(_wallet, _id); emit PendingTransferCanceled(_wallet, _id); } /** * @dev Lets the owner of a wallet change its global limit. * The limit is expressed in ETH. Changes to the limit take 24 hours. * @param _wallet The target wallet. * @param _newLimit The new limit. */ function changeLimit(BaseWallet _wallet, uint256 _newLimit) public onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { changeLimit(_wallet, _newLimit, securityPeriod); } /** * @dev Convenience method to disable the limit * The limit is disabled by setting it to an arbitrary large value. * @param _wallet The target wallet. */ function disableLimit(BaseWallet _wallet) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { changeLimit(_wallet, LIMIT_DISABLED, securityPeriod); } /** * @dev Checks if an address is whitelisted for a wallet. * @param _wallet The target wallet. * @param _target The address. * @return true if the address is whitelisted. */ function isWhitelisted(BaseWallet _wallet, address _target) public view returns (bool _isWhitelisted) { uint whitelistAfter = transferStorage.getWhitelist(_wallet, _target); // solium-disable-next-line security/no-block-members return whitelistAfter > 0 && whitelistAfter < now; } /** * @dev Gets the info of a pending transfer for a wallet. * @param _wallet The target wallet. * @param _id The pending transfer Id. * @return the epoch time at which the pending transfer can be executed. */ function getPendingTransfer(BaseWallet _wallet, bytes32 _id) external view returns (uint64 _executeAfter) { _executeAfter = uint64(configs[_wallet].pendingTransfers[_id]); } // *************** Internal Functions ********************* // /** * @dev Helper method to transfer ETH for a wallet. * @param _wallet The target wallet. * @param _to The recipient. * @param _value The amount of ETH to transfer * @param _data The data to *log* with the transfer. */ function transferETH(BaseWallet _wallet, address _to, uint256 _value, bytes _data) internal { _wallet.invoke(_to, _value, EMPTY_BYTES); emit Transfer(_wallet, ETH_TOKEN, _value, _to, _data); } /** * @dev Helper method to transfer ERC20 for a wallet. * @param _wallet The target wallet. * @param _token The ERC20 address. * @param _to The recipient. * @param _value The amount of token to transfer * @param _data The data to pass with the trnasfer. */ function transferERC20(BaseWallet _wallet, address _token, address _to, uint256 _value, bytes _data) internal { bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", _to, _value); _wallet.invoke(_token, 0, methodData); emit Transfer(_wallet, _token, _value, _to, _data); } /** * @dev Creates a new pending transfer for a wallet. * @param _wallet The target wallet. * @param _token The token for the transfer. * @param _to The recipient for the transfer. * @param _amount The amount of token to transfer. * @param _data The data associated to the transfer. * @return the identifier for the new pending transfer. */ function addPendingTransfer(BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data) internal returns (bytes32) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, block.number)); uint executeAfter = now.add(securityPeriod); configs[_wallet].pendingTransfers[id] = executeAfter; emit PendingTransferCreated(_wallet, id, executeAfter, _token, _to, _amount, _data); } /** * @dev Removes an existing pending transfer. * @param _wallet The target wallet * @param _id The id of the transfer to remove. */ function removePendingTransfer(BaseWallet _wallet, bytes32 _id) internal { delete configs[_wallet].pendingTransfers[_id]; } // *************** Implementation of RelayerModule methods ********************* // // Overrides refund to add the refund in the daily limit. function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { // 21000 (transaction) + 7620 (execution of refund) + 7324 (execution of updateDailySpent) + 672 to log the event + _gasUsed uint256 amount = 36616 + _gasUsed; if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } updateDailySpent(_wallet, uint128(getCurrentLimit(_wallet)), amount); _wallet.invoke(_relayer, amount, ""); } } // Overrides verifyRefund to add the refund in the daily limit. function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 0 && ( address(_wallet).balance < _gasUsed * _gasPrice || isWithinDailyLimit(_wallet, getCurrentLimit(_wallet), _gasUsed * _gasPrice) == false || _wallet.authorised(this) == false )) { return false; } return true; } // Overrides to use the incremental nonce and save some gas function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { return checkAndUpdateNonce(_wallet, _nonce); } function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool) { address signer = recoverSigner(_signHash, _signatures, 0); return isOwner(_wallet, signer); // "TT: signer must be owner" } function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256) { bytes4 methodId = functionPrefix(_data); if (methodId == EXECUTE_PENDING_PREFIX) { return 0; } return 1; } }
* @title TokenTransfer @dev Module to transfer tokens (ETH or ERC20) based on a security context (daily limit, whitelist, etc). @author Julien Niset - <[email protected]>/ Mock token address for ETH large limit when the limit can be considered disabled
contract TokenTransfer is BaseModule, RelayerModule, LimitManager { bytes32 constant NAME = "TokenTransfer"; bytes4 constant internal EXECUTE_PENDING_PREFIX = bytes4(keccak256("executePendingTransfer(address,address,address,uint256,bytes,uint256)")); bytes constant internal EMPTY_BYTES = ""; using SafeMath for uint256; address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenTransferConfig { mapping (bytes32 => uint256) pendingTransfers; } event Transfer(address indexed wallet, address indexed token, uint256 indexed amount, address to, bytes data); event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter); event RemovedFromWhitelist(address indexed wallet, address indexed target); event PendingTransferCreated(address indexed wallet, bytes32 indexed id, uint256 indexed executeAfter, address token, address to, uint256 amount, bytes data); event PendingTransferExecuted(address indexed wallet, bytes32 indexed id); event PendingTransferCanceled(address indexed wallet, bytes32 indexed id); mapping (address => TokenTransferConfig) internal configs; uint256 public securityPeriod; uint256 public securityWindow; GuardianStorage public guardianStorage; TransferStorage public transferStorage; TokenPriceProvider public priceProvider; modifier onlyOwnerOrModule(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender) || _wallet.authorised(msg.sender), "TT: must be wallet owner or module"); _; } modifier onlyWhenUnlocked(BaseWallet _wallet) { require(!guardianStorage.isLocked(_wallet), "TT: wallet must be unlocked"); _; } constructor( ModuleRegistry _registry, TransferStorage _transferStorage, GuardianStorage _guardianStorage, address _priceProvider, uint256 _securityPeriod, uint256 _securityWindow, uint256 _defaultLimit ) BaseModule(_registry, NAME) LimitManager(_defaultLimit) public { transferStorage = _transferStorage; guardianStorage = _guardianStorage; priceProvider = TokenPriceProvider(_priceProvider); securityPeriod = _securityPeriod; securityWindow = _securityWindow; } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function transferToken( BaseWallet _wallet, address _token, address _to, uint256 _amount, bytes _data ) external onlyOwnerOrModule(_wallet) onlyWhenUnlocked(_wallet) { if(isWhitelisted(_wallet, _to)) { if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } } else { if(_token == ETH_TOKEN) { if (checkAndUpdateDailySpent(_wallet, _amount)) { transferETH(_wallet, _to, _amount, _data); } else { addPendingTransfer(_wallet, ETH_TOKEN, _to, _amount, _data); } } else { uint256 etherAmount = priceProvider.getEtherValue(_amount, _token); if (checkAndUpdateDailySpent(_wallet, etherAmount)) { transferERC20(_wallet, _token, _to, _amount, _data); } else { addPendingTransfer(_wallet, _token, _to, _amount, _data); } } } } function addToWhitelist( BaseWallet _wallet, address _target ) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(!isWhitelisted(_wallet, _target), "TT: target already whitelisted"); uint256 whitelistAfter = now.add(securityPeriod); transferStorage.setWhitelist(_wallet, _target, whitelistAfter); emit AddedToWhitelist(_wallet, _target, uint64(whitelistAfter)); } function removeFromWhitelist( BaseWallet _wallet, address _target ) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(isWhitelisted(_wallet, _target), "TT: target not whitelisted"); transferStorage.setWhitelist(_wallet, _target, 0); emit RemovedFromWhitelist(_wallet, _target); } function executePendingTransfer( BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data, uint _block ) public onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, _block)); uint executeAfter = configs[_wallet].pendingTransfers[id]; uint executeBefore = executeAfter.add(securityWindow); require(executeAfter <= now && now <= executeBefore, "TT: outside of the execution window"); removePendingTransfer(_wallet, id); if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } emit PendingTransferExecuted(_wallet, id); } function executePendingTransfer( BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data, uint _block ) public onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, _block)); uint executeAfter = configs[_wallet].pendingTransfers[id]; uint executeBefore = executeAfter.add(securityWindow); require(executeAfter <= now && now <= executeBefore, "TT: outside of the execution window"); removePendingTransfer(_wallet, id); if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } emit PendingTransferExecuted(_wallet, id); } function executePendingTransfer( BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data, uint _block ) public onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, _block)); uint executeAfter = configs[_wallet].pendingTransfers[id]; uint executeBefore = executeAfter.add(securityWindow); require(executeAfter <= now && now <= executeBefore, "TT: outside of the execution window"); removePendingTransfer(_wallet, id); if(_token == ETH_TOKEN) { transferETH(_wallet, _to, _amount, _data); } else { transferERC20(_wallet, _token, _to, _amount, _data); } emit PendingTransferExecuted(_wallet, id); } function cancelPendingTransfer( BaseWallet _wallet, bytes32 _id ) public onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { require(configs[_wallet].pendingTransfers[_id] > 0, "TT: unknown pending transfer"); removePendingTransfer(_wallet, _id); emit PendingTransferCanceled(_wallet, _id); } function changeLimit(BaseWallet _wallet, uint256 _newLimit) public onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { changeLimit(_wallet, _newLimit, securityPeriod); } function disableLimit(BaseWallet _wallet) external onlyOwner(_wallet) onlyWhenUnlocked(_wallet) { changeLimit(_wallet, LIMIT_DISABLED, securityPeriod); } function isWhitelisted(BaseWallet _wallet, address _target) public view returns (bool _isWhitelisted) { uint whitelistAfter = transferStorage.getWhitelist(_wallet, _target); return whitelistAfter > 0 && whitelistAfter < now; } function getPendingTransfer(BaseWallet _wallet, bytes32 _id) external view returns (uint64 _executeAfter) { _executeAfter = uint64(configs[_wallet].pendingTransfers[_id]); } function transferETH(BaseWallet _wallet, address _to, uint256 _value, bytes _data) internal { _wallet.invoke(_to, _value, EMPTY_BYTES); emit Transfer(_wallet, ETH_TOKEN, _value, _to, _data); } function transferERC20(BaseWallet _wallet, address _token, address _to, uint256 _value, bytes _data) internal { bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", _to, _value); _wallet.invoke(_token, 0, methodData); emit Transfer(_wallet, _token, _value, _to, _data); } function addPendingTransfer(BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data) internal returns (bytes32) { bytes32 id = keccak256(abi.encodePacked(_token, _to, _amount, _data, block.number)); uint executeAfter = now.add(securityPeriod); configs[_wallet].pendingTransfers[id] = executeAfter; emit PendingTransferCreated(_wallet, id, executeAfter, _token, _to, _amount, _data); } function removePendingTransfer(BaseWallet _wallet, bytes32 _id) internal { delete configs[_wallet].pendingTransfers[_id]; } function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 36616 + _gasUsed; if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } updateDailySpent(_wallet, uint128(getCurrentLimit(_wallet)), amount); _wallet.invoke(_relayer, amount, ""); } } function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 36616 + _gasUsed; if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } updateDailySpent(_wallet, uint128(getCurrentLimit(_wallet)), amount); _wallet.invoke(_relayer, amount, ""); } } function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 36616 + _gasUsed; if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } updateDailySpent(_wallet, uint128(getCurrentLimit(_wallet)), amount); _wallet.invoke(_relayer, amount, ""); } } function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 36616 + _gasUsed; if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } updateDailySpent(_wallet, uint128(getCurrentLimit(_wallet)), amount); _wallet.invoke(_relayer, amount, ""); } } function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 0 && ( address(_wallet).balance < _gasUsed * _gasPrice || isWithinDailyLimit(_wallet, getCurrentLimit(_wallet), _gasUsed * _gasPrice) == false || _wallet.authorised(this) == false )) { return false; } return true; } function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 0 && ( address(_wallet).balance < _gasUsed * _gasPrice || isWithinDailyLimit(_wallet, getCurrentLimit(_wallet), _gasUsed * _gasPrice) == false || _wallet.authorised(this) == false )) { return false; } return true; } function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { return checkAndUpdateNonce(_wallet, _nonce); } function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool) { address signer = recoverSigner(_signHash, _signatures, 0); } function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256) { bytes4 methodId = functionPrefix(_data); if (methodId == EXECUTE_PENDING_PREFIX) { return 0; } return 1; } function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256) { bytes4 methodId = functionPrefix(_data); if (methodId == EXECUTE_PENDING_PREFIX) { return 0; } return 1; } }
5,456,336
[ 1, 1345, 5912, 225, 5924, 358, 7412, 2430, 261, 1584, 44, 578, 4232, 39, 3462, 13, 2511, 603, 279, 4373, 819, 261, 26790, 1800, 16, 10734, 16, 5527, 2934, 225, 804, 14826, 275, 423, 291, 278, 300, 411, 28034, 275, 36, 3175, 319, 18, 17177, 16893, 7867, 1147, 1758, 364, 512, 2455, 7876, 1800, 1347, 326, 1800, 848, 506, 7399, 5673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 5912, 353, 3360, 3120, 16, 4275, 1773, 3120, 16, 7214, 1318, 288, 203, 203, 565, 1731, 1578, 5381, 6048, 273, 315, 1345, 5912, 14432, 203, 203, 565, 1731, 24, 5381, 2713, 24508, 9099, 67, 25691, 67, 6307, 273, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 8837, 8579, 5912, 12, 2867, 16, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 16, 11890, 5034, 2225, 10019, 203, 203, 565, 1731, 5381, 2713, 8984, 67, 13718, 273, 1408, 31, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 5381, 2713, 512, 2455, 67, 8412, 273, 374, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 31, 203, 203, 565, 1958, 3155, 5912, 809, 288, 203, 3639, 2874, 261, 3890, 1578, 516, 2254, 5034, 13, 4634, 1429, 18881, 31, 203, 565, 289, 203, 203, 203, 203, 565, 871, 12279, 12, 2867, 8808, 9230, 16, 1758, 8808, 1147, 16, 2254, 5034, 8808, 3844, 16, 1758, 358, 16, 1731, 501, 1769, 377, 203, 565, 871, 25808, 774, 18927, 12, 2867, 8808, 9230, 16, 1758, 8808, 1018, 16, 2254, 1105, 10734, 4436, 1769, 203, 565, 871, 2663, 9952, 1265, 18927, 12, 2867, 8808, 9230, 16, 1758, 8808, 1018, 1769, 203, 565, 871, 16034, 5912, 6119, 12, 2867, 8808, 9230, 16, 1731, 1578, 8808, 612, 16, 2254, 5034, 8808, 1836, 4436, 16, 1758, 1147, 16, 1758, 358, 16, 2254, 5034, 3844, 16, 1731, 501, 1769, 2 ]
./partial_match/56/0x2b28688e290aF66Fbf67280937399140B5F1Dda3/sources/BerryMaster.sol
* @dev Getter for the total_supply of oracle tokens @return uint total supply/
function totalSupply(BerryStorage.BerryStorageStruct storage self) internal view returns (uint256) { return self.uintVars[keccak256("total_supply")]; }
11,056,992
[ 1, 8461, 364, 326, 2078, 67, 2859, 1283, 434, 20865, 2430, 327, 2254, 2078, 14467, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 12, 38, 21938, 3245, 18, 38, 21938, 3245, 3823, 2502, 365, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 365, 18, 11890, 5555, 63, 79, 24410, 581, 5034, 2932, 4963, 67, 2859, 1283, 7923, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.5; contract Better_Bank_With_Interest { // //////////////////////////////////////////////////////////////// // // A term deposit bank that pays interest on withdrawal // // v0.02 beta, use AT OWN RISK - I am not refunding any lost ether! // And check the code before depositing anything. // // How to use: 1) transfer min. 250 ether using the deposit() function (5 ether deposit fee per deposit) // note: minimum ether amount and deposit fee can change, so check public variables // - minimum_deposit_amount // - deposit_fee // before depositing! // // 2) withdraw after 5 days, receive up to 10% interest (1 additional ether for every 10 ether withdrawal) // note: to get most of the interest paid out, withdraw in lots of 10 ether... // /////////////////////////////////////////////////////////////////// // // Now you may ask - where do the extra ether come from? :) // The answer is simple: From people who dont follow the instructions properly! // And there are usually plenty of those... // // Common pitfalls: // e.g. - deposit to the fallback function instead of the proper deposit() function // - withdraw MORE than 10 ether AT A TIME ... (that just means you get less interest paid out) // - or you wait too long after your term deposit ended, and other people have drained the interest pool. // // You can always check the availbale interest amount using get_available_interest_amount () before you withdraw // And be quick - everyone gets the same 30850 block term deposit time (~5 days) until they can withdraw. // // Also FYI: The bank cannot remove money from the interest pool until the end of the contract life. // And make sure you withdraw your balances before the end of the contract life also. // Check public contract_alive_until_this_block variable to find out when the contract life ends. // Initial end date is block #3000000 (~Mid Jan 2017), but the bank can extend that life. // Note: the bank can only EXTEND that end date, not shorten it. // // And here we go - happy reading: // // store of all account balances mapping(address => uint256) balances; mapping(address => uint256) term_deposit_end_block; // store per address the minimum time for the term deposit // address thebank; // the bank uint256 public minimum_deposit_amount; // minimum deposits uint256 public deposit_fee; // fee for deposits uint256 public contract_alive_until_this_block; uint256 public count_customer_deposits; function Better_Bank_With_Interest() { // create the contract thebank = msg.sender; minimum_deposit_amount = 250 ether; deposit_fee = 5 ether; contract_alive_until_this_block = 3000000; // around 2 months from now (mid Jan 2017) // --> can be extended but not brought forward // count_customer_deposits = 0; // bank cannot touch remaining interest balance until the contract has reached end of life. term_deposit_end_block[thebank] = 0;// contract_alive_until_this_block; // } ////////////////////////////////////////////////////////////////////////////////////////// // deposit ether into term-deposit account ////////////////////////////////////////////////////////////////////////////////////////// function deposit() payable { // if (msg.value < minimum_deposit_amount) throw; // minimum deposit is at least minimum_payment. // // no fee for first payment (if the customers's balance is 0) if (balances[msg.sender] == 0) deposit_fee = 0 ether; // if ( msg.sender == thebank ){ // thebank is depositing into bank/interest account, without fee balances[thebank] += msg.value; } else { // customer deposit count_customer_deposits += 1; // count deposits, cannot remove contract any more until end of life balances[msg.sender] += msg.value - deposit_fee; // credit the sender's account balances[thebank] += deposit_fee; // difference (fee) to be credited to thebank term_deposit_end_block[msg.sender] = block.number + 30850; // approx 5 days ( 5 * 86400/14 ); } // } ////////////////////////////////////////////////////////////////////////////////////////// // withdraw from account, with 10 ether interest (after term deposit end) ////////////////////////////////////////////////////////////////////////////////////////// // function withdraw(uint256 withdraw_amount) { // if (withdraw_amount < 10 ether) throw; // minimum withdraw amount is 10 ether if ( withdraw_amount > balances[msg.sender] ) throw; // cannot withdraw more than in customer balance if (block.number < term_deposit_end_block[msg.sender] ) throw; // cannot withdraw until the term deposit has ended // Note: thebank/interest account cannot be withdrawed from until contract end-of life. // thebank's term-deposit end block is the same as contract_alive_until_this_block // uint256 interest = 1 ether; // 1 ether interest paid at time of withdrawal // if (msg.sender == thebank){ // but no interest for thebank (who can't withdraw until block contract_alive_until_this_block anyways) interest = 0 ether; } // if (interest > balances[thebank]) // cant pay more interest than available in the thebank/bank interest = balances[thebank]; // so send whatever is left anyways // // balances[thebank] -= interest; // reduce thebank balance, and send bonus to customer balances[msg.sender] -= withdraw_amount; // if (!msg.sender.send(withdraw_amount)) throw; // send withdraw amount, but check for error to roll back if needed if (!msg.sender.send(interest)) throw; // send interest amount, but check for error to roll back if needed // } //////////////////////////////////////////////////////////////////////////// // HELPER FUNCTIONS //////////////////////////////////////////////////////////////////////////// // set minimum deposit limits function set_minimum_payment(uint256 new_limit) { if ( msg.sender == thebank ){ minimum_deposit_amount = new_limit; } } // // change deposit fee function set_deposit_fee (uint256 new_fee) { if ( msg.sender == thebank ){ deposit_fee = new_fee; } } // find out how much money is available for interest payments function get_available_interest_amount () constant returns (uint256) { return balances[thebank]; } // find out what the end date of the customers term deposit is function get_term_deposit_end_date (address query_address) constant returns (uint256) { return term_deposit_end_block[query_address]; } // find out how much money is available for interest payments function get_balance (address query_address) constant returns (uint256) { return balances[query_address]; } // //////////////////////////////////////////////////////////////// // this bank won't live forever, so this will handle the exit (or extend its life) //////////////////////////////////////////////////////////// // function extend_life_of_contract (uint256 newblock){ if ( msg.sender != thebank || newblock < contract_alive_until_this_block ) throw; // can only extend contract_alive_until_this_block = newblock; // lock thebank/interest account until new end date term_deposit_end_block[thebank] = contract_alive_until_this_block; } // // the self destruct after the final block number has been reached (or immediately if there havent been any customer payments yet) function close_bank(){ if (contract_alive_until_this_block < block.number || count_customer_deposits == 0) selfdestruct(thebank); // any funds still remaining within the bank will be sent to the creator // --> bank customers have to make sure they withdraw their $$$ before the final block. } //////////////////////////////////////////////////////////////// // fallback function //////////////////////////////////////////////////////////// function () payable { // any unidentified payments (that didnt call the deposit function) // go into the standard interest account of the bank // and become available for interest withdrawal by bank users balances[thebank] += msg.value; } }
difference (fee) to be credited to thebank
balances[thebank] += deposit_fee;
12,642,356
[ 1, 23444, 261, 21386, 13, 358, 506, 12896, 329, 358, 326, 10546, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 324, 26488, 63, 5787, 10546, 65, 1011, 443, 1724, 67, 21386, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.7; pragma experimental ABIEncoderV2; contract ControllerV4 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant burn = 0x000000000000000000000000000000000000dEaD; address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; address public governance; address public strategist; address public devfund; address public treasury; address public timelock; // Convenience fee 0.1% uint256 public convenienceFee = 100; uint256 public constant convenienceFeeMax = 100000; mapping(address => address) public jars; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public approvedJarConverters; uint256 public split = 500; uint256 public constant max = 10000; constructor( address _governance, address _strategist, address _timelock, address _devfund, address _treasury ) public { governance = _governance; strategist = _strategist; timelock = _timelock; devfund = _devfund; treasury = _treasury; } function setDevFund(address _devfund) public { require(msg.sender == governance, "!governance"); devfund = _devfund; } function setTreasury(address _treasury) public { require(msg.sender == governance, "!governance"); treasury = _treasury; } function setStrategist(address _strategist) public { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setJar(address _token, address _jar) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(jars[_token] == address(0), "jar"); jars[_token] = _jar; } function approveJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = true; } function revokeJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = false; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = false; } function setConvenienceFee(uint256 _convenienceFee) external { require(msg.sender == timelock, "!timelock"); convenienceFee = _convenienceFee; } function setStrategy(address _token, address _strategy) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(approvedStrategies[_token][_strategy] == true, "!approved"); address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return IStrategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); IStrategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IStrategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = IStrategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn( _token, _want, _balance, parts, 0 ); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == jars[_token], "!jar"); IStrategy(strategies[_token]).withdraw(_amount); } // Function to swap between jars function swapExactJarForJar( address _fromJar, // From which Jar address _toJar, // To which Jar uint256 _fromJarAmount, // How much jar tokens to swap uint256 _toJarMinAmount, // How much jar tokens you'd like at a minimum address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); // Only return last response for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedJarConverters[_targets[i]], "!converter"); } address _fromJarToken = IJar(_fromJar).token(); address _toJarToken = IJar(_toJar).token(); // Get pTokens from msg.sender IERC20(_fromJar).safeTransferFrom( msg.sender, address(this), _fromJarAmount ); // Calculate how much underlying // is the amount of pTokens worth uint256 _fromJarUnderlyingAmount = _fromJarAmount .mul(IJar(_fromJar).getRatio()) .div(10**uint256(IJar(_fromJar).decimals())); // Call 'withdrawForSwap' on Jar's current strategy if Jar // doesn't have enough initial capital. // This has moves the funds from the strategy to the Jar's // 'earnable' amount. Enabling 'free' withdrawals uint256 _fromJarAvailUnderlying = IERC20(_fromJarToken).balanceOf( _fromJar ); if (_fromJarAvailUnderlying < _fromJarUnderlyingAmount) { IStrategy(strategies[_fromJarToken]).withdrawForSwap( _fromJarUnderlyingAmount.sub(_fromJarAvailUnderlying) ); } // Withdraw from Jar // Note: this is free since its still within the "earnable" amount // as we transferred the access IERC20(_fromJar).safeApprove(_fromJar, 0); IERC20(_fromJar).safeApprove(_fromJar, _fromJarAmount); IJar(_fromJar).withdraw(_fromJarAmount); // Calculate fee uint256 _fromUnderlyingBalance = IERC20(_fromJarToken).balanceOf( address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromJarToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromJarToken).safeTransfer(treasury, _convenienceFee.div(2)); } // Executes sequence of logic for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } // Deposit into new Jar uint256 _toBal = IERC20(_toJarToken).balanceOf(address(this)); IERC20(_toJarToken).safeApprove(_toJar, 0); IERC20(_toJarToken).safeApprove(_toJar, _toBal); IJar(_toJar).deposit(_toBal); // Send Jar Tokens to user uint256 _toJarBal = IJar(_toJar).balanceOf(address(this)); if (_toJarBal < _toJarMinAmount) { revert("!min-jar-amount"); } IJar(_toJar).transfer(msg.sender, _toJarBal); return _toJarBal; } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } } contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } } interface ICToken { function totalSupply() external view returns (uint256); function totalBorrows() external returns (uint256); function borrowIndex() external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } interface ICEther { function mint() external payable; /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable; /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable; /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } interface IComptroller { function compAccrued(address) external view returns (uint256); function compSupplierIndex(address, address) external view returns (uint256); function compBorrowerIndex(address, address) external view returns (uint256); function compSpeeds(address) external view returns (uint256); function compBorrowState(address) external view returns (uint224, uint32); function compSupplyState(address) external view returns (uint224, uint32); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; // Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows function claimComp( address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers ) external; function markets(address cTokenAddress) external view returns (bool, uint256); } interface ICompoundLens { function getCompBalanceMetadataExt( address comp, address comptroller, address account ) external returns ( uint256 balance, uint256 votes, address delegate, uint256 allocated ); } interface IController { function jars(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } interface Converter { function convert(address) external returns (uint256); } interface ICurveFi_2 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveFi_3 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[3] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); } interface ICurveFi_4 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveZap_4 { function add_liquidity( uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance( uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function withdraw_donated_dust() external; function coins(int128 arg0) external returns (address); function underlying_coins(int128 arg0) external returns (address); function curve() external returns (address); function token() external returns (address); } interface ICurveZap { function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); } interface ICurveMintr { function mint(address) external; function minted(address arg0, address arg1) external view returns (uint256); } interface ICurveVotingEscrow { function locked(address arg0) external view returns (int128 amount, uint256 end); function locked__end(address _addr) external view returns (uint256); function create_lock(uint256, uint256) external; function increase_amount(uint256) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function smart_wallet_checker() external returns (address); } interface ICurveSmartContractChecker { function wallets(address) external returns (bool); function approveWallet(address _wallet) external; } interface IJarConverter { function convert( address _refundExcess, // address to send the excess amount when adding liquidity uint256 _amount, // UNI LP Amount bytes calldata _data ) external returns (uint256); } interface IMasterchef { function BONUS_MULTIPLIER() external view returns (uint256); function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function dev(address _devaddr) external; function devFundDivRate() external view returns (uint256); function devaddr() external view returns (address); function emergencyWithdraw(uint256 _pid) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function massUpdatePools() external; function owner() external view returns (address); function pendingPickle(uint256 _pid, address _user) external view returns (uint256); function pickle() external view returns (address); function picklePerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accPicklePerShare ); function poolLength() external view returns (uint256); function renounceOwnership() external; function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function setBonusEndBlock(uint256 _bonusEndBlock) external; function setDevFundDivRate(uint256 _devFundDivRate) external; function setPicklePerBlock(uint256 _picklePerBlock) external; function startBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function transferOwnership(address newOwner) external; function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw(uint256 _pid, uint256 _amount) external; } interface OneSplitAudit { function getExpectedReturn( address fromToken, address toToken, uint256 amount, uint256 parts, uint256 featureFlags ) external view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address toToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 featureFlags ) external payable; } interface Proxy { function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory); function increaseAmount(uint256) external; } interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } interface IStakingRewardsFactory { function deploy(address stakingToken, uint256 rewardAmount) external; function isOwner() external view returns (bool); function notifyRewardAmount(address stakingToken) external; function notifyRewardAmounts() external; function owner() external view returns (address); function renounceOwnership() external; function rewardsToken() external view returns (address); function stakingRewardsGenesis() external view returns (uint256); function stakingRewardsInfoByStakingToken(address) external view returns (address stakingRewards, uint256 rewardAmount); function stakingTokens(uint256) external view returns (address); function transferOwnership(address newOwner) external; } interface IStrategy { function rewards() external view returns (address); function gauge() external view returns (address); function want() external view returns (address); function timelock() external view returns (address); function deposit() external; function withdrawForSwap(uint256) external returns (uint256); function withdraw(address) external; function withdraw(uint256) external; function skim() external; function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function harvest() external; function setTimelock(address) external; function setController(address _controller) external; function execute(address _target, bytes calldata _data) external payable returns (bytes memory response); function execute(bytes calldata _data) external payable returns (bytes memory response); } interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } interface USDT { function approve(address guy, uint256 wad) external; function transfer(address _to, uint256 _value) external; } interface WETH { function name() external view returns (string memory); function approve(address guy, uint256 wad) external returns (bool); function totalSupply() external view returns (uint256); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); function withdraw(uint256 wad) external; function decimals() external view returns (uint8); function balanceOf(address) external view returns (uint256); function symbol() external view returns (string memory); function transfer(address dst, uint256 wad) external returns (bool); function deposit() external payable; function allowance(address, address) external view returns (uint256); } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } 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); } 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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); 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); } } } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } 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"); } } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require( msg.sender == owner, "Only the contract owner may perform this action" ); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } abstract contract Pausable is Owned { uint256 public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require( !paused, "This action cannot be performed while the contract is paused" ); _; } } 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; } } 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; } } contract PickleJar is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public governance; address public timelock; address public controller; constructor(address _token, address _governance, address _timelock, address _controller) public ERC20( string(abi.encodePacked("pickling ", ERC20(_token).name())), string(abi.encodePacked("p", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); governance = _governance; timelock = _timelock; controller = _controller; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) public { require(msg.sender == timelock, "!timelock"); controller = _controller; } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } } contract PickleSwap { using SafeERC20 for IERC20; UniswapRouterV2 router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function convertWETHPair( address fromLP, address toLP, uint256 value ) public { IUniswapV2Pair fromPair = IUniswapV2Pair(fromLP); IUniswapV2Pair toPair = IUniswapV2Pair(toLP); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } if (!(toPair.token0() == weth || toPair.token1() == weth)) { revert("!eth-to"); } // Get non-eth token from pairs address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); address _to = toPair.token0() != weth ? toPair.token0() : toPair.token1(); // Transfer IERC20(fromLP).safeTransferFrom(msg.sender, address(this), value); // Remove liquidity IERC20(fromLP).safeApprove(address(router), 0); IERC20(fromLP).safeApprove(address(router), value); router.removeLiquidity( fromPair.token0(), fromPair.token1(), value, 0, 0, address(this), now + 60 ); // Convert to target token address[] memory path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Supply liquidity IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); IERC20(_to).safeApprove(address(router), 0); IERC20(_to).safeApprove(address(router), uint256(-1)); router.addLiquidity( weth, _to, IERC20(weth).balanceOf(address(this)), IERC20(_to).balanceOf(address(this)), 0, 0, msg.sender, now + 60 ); // Refund sender any remaining tokens IERC20(weth).safeTransfer( msg.sender, IERC20(weth).balanceOf(address(this)) ); IERC20(_to).safeTransfer(msg.sender, IERC20(_to).balanceOf(address(this))); } } contract CurveProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; function remove_liquidity_one_coin( address curve, address curveLp, int128 index ) public { uint256 lpAmount = IERC20(curveLp).balanceOf(address(this)); IERC20(curveLp).safeApprove(curve, 0); IERC20(curveLp).safeApprove(curve, lpAmount); ICurveZap(curve).remove_liquidity_one_coin(lpAmount, index, 0); } function add_liquidity( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) public { uint256 underlyingAmount = IERC20(underlying).balanceOf(address(this)); // curveFunctionSig should be the abi.encodedFormat of // add_liquidity(uint256[N_COINS],uint256) // The reason why its here is because different curve pools // have a different function signature uint256[] memory liquidity = new uint256[](curvePoolSize); liquidity[curveUnderlyingIndex] = underlyingAmount; bytes memory callData = abi.encodePacked( curveFunctionSig, liquidity, uint256(0) ); IERC20(underlying).safeApprove(curve, 0); IERC20(underlying).safeApprove(curve, underlyingAmount); (bool success, ) = curve.call(callData); require(success, "!success"); } } contract UniswapV2ProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Factory public constant factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); UniswapRouterV2 public constant router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function getSwapAmt(uint256 amtA, uint256 resA) internal pure returns (uint256) { return sqrt(amtA.mul(resA.mul(3988000).add(amtA.mul(3988009)))) .sub(amtA.mul(1997)) .div(1994); } // https://blog.alphafinance.io/onesideduniswap/ // https://github.com/AlphaFinanceLab/alphahomora/blob/88a8dfe4d4fa62b13b40f7983ee2c646f83e63b5/contracts/StrategyAddETHOnly.sol#L39 // AlphaFinance is gripbook licensed function optimalOneSideSupply( IUniswapV2Pair pair, address from, address to ) public { address[] memory path = new address[](2); // 1. Compute optimal amount of WETH to be converted (uint256 r0, uint256 r1, ) = pair.getReserves(); uint256 rIn = pair.token0() == from ? r0 : r1; uint256 aIn = getSwapAmt(rIn, IERC20(from).balanceOf(address(this))); // 2. Convert that from -> to path[0] = from; path[1] = to; IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), aIn); router.swapExactTokensForTokens(aIn, 0, path, address(this), now + 60); } function swapUniswap(address from, address to) public { require(to != address(0)); address[] memory path; if (from == weth || to == weth) { path = new address[](2); path[0] = from; path[1] = to; } else { path = new address[](3); path[0] = from; path[1] = weth; path[2] = to; } uint256 amount = IERC20(from).balanceOf(address(this)); IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), amount); router.swapExactTokensForTokens( amount, 0, path, address(this), now + 60 ); } function removeLiquidity(IUniswapV2Pair pair) public { uint256 _balance = pair.balanceOf(address(this)); pair.approve(address(router), _balance); router.removeLiquidity( pair.token0(), pair.token1(), _balance, 0, 0, address(this), now + 60 ); } function supplyLiquidity( address token0, address token1 ) public returns (uint256) { // Add liquidity to uniswap IERC20(token0).safeApprove(address(router), 0); IERC20(token0).safeApprove( address(router), IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeApprove(address(router), 0); IERC20(token1).safeApprove( address(router), IERC20(token1).balanceOf(address(this)) ); (, , uint256 _to) = router.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); return _to; } function refundDust(IUniswapV2Pair pair, address recipient) public { address token0 = pair.token0(); address token1 = pair.token1(); IERC20(token0).safeTransfer( recipient, IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeTransfer( recipient, IERC20(token1).balanceOf(address(this)) ); } function lpTokensToPrimitive( IUniswapV2Pair from, address to ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); // Removes liquidity removeLiquidity(from); // Swap from WETH to other swapUniswap(weth, to); // If from is not to, we swap them too if (fromOther != to) { swapUniswap(fromOther, to); } } function primitiveToLpTokens( address from, IUniswapV2Pair to, address dustRecipient ) public { if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address toOther = to.token0() == weth ? to.token1() : to.token0(); // Swap to WETH swapUniswap(from, weth); // Optimal supply from WETH to optimalOneSideSupply(to, weth, toOther); // Supply tokens supplyLiquidity(weth, toOther); // Dust refundDust(to, dustRecipient); } function swapUniLPTokens( IUniswapV2Pair from, IUniswapV2Pair to, address dustRecipient ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); address toOther = to.token0() == weth ? to.token1() : to.token0(); // Remove weth-<token> pair removeLiquidity(from); // Swap <token> to WETH swapUniswap(fromOther, weth); // Optimal supply from WETH to <other-token> optimalOneSideSupply(to, weth, toOther); // Supply weth-<other-token> pair supplyLiquidity(weth, toOther); // Refund dust refundDust(to, dustRecipient); } } contract StakingRewards is ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken, address _stakingToken ) public Owned(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } function min(uint256 a, uint256 b) public pure returns (uint256) { return a < b ? a : b; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( tokenAddress != address(stakingToken) && tokenAddress != address(rewardsToken), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); } contract CRVLocker { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address public governance; mapping(address => bool) public voters; constructor(address _governance) public { governance = _governance; } function getName() external pure returns (string memory) { return "CRVLocker"; } function addVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = true; } function removeVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = false; } function withdraw(address _asset) external returns (uint256 balance) { require(voters[msg.sender], "!voter"); balance = IERC20(_asset).balanceOf(address(this)); IERC20(_asset).safeTransfer(msg.sender, balance); } function createLock(uint256 _value, uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).create_lock(_value, _unlockTime); } function increaseAmount(uint256 _value) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).increase_amount(_value); } function increaseUnlockTime(uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).increase_unlock_time(_unlockTime); } function release() external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).withdraw(); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory) { require(voters[msg.sender] || msg.sender == governance, "!governance"); (bool success, bytes memory result) = to.call{value: value}(data); require(success, "!execute-success"); return (success, result); } } contract SCRVVoter { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; CRVLocker public crvLocker; address public constant want = 0xC25a3A3b969415c80451098fa907EC722572917F; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address public constant gaugeController = 0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB; address public constant scrvGauge = 0xA90996896660DEcC6E997655E065b23788857849; mapping(address => bool) public strategies; address public governance; constructor(address _governance, address _crvLocker) public { governance = _governance; crvLocker = CRVLocker(_crvLocker); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function approveStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = true; } function revokeStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = false; } function lock() external { crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); } function vote(address _gauge, uint256 _amount) public { require(strategies[msg.sender], "!strategy"); crvLocker.execute( gaugeController, 0, abi.encodeWithSignature( "vote_for_gauge_weights(address,uint256)", _gauge, _amount ) ); } function max() external { require(strategies[msg.sender], "!strategy"); vote(scrvGauge, 10000); } function withdraw( address _gauge, address _token, uint256 _amount ) public returns (uint256) { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("withdraw(uint256)", _amount) ); uint256 _after = IERC20(_token).balanceOf(address(crvLocker)); uint256 _net = _after.sub(_before); crvLocker.execute( _token, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _net ) ); return _net; } function balanceOf(address _gauge) public view returns (uint256) { return IERC20(_gauge).balanceOf(address(crvLocker)); } function withdrawAll(address _gauge, address _token) external returns (uint256) { require(strategies[msg.sender], "!strategy"); return withdraw(_gauge, _token, balanceOf(_gauge)); } function deposit(address _gauge, address _token) external { uint256 _balance = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(address(crvLocker), _balance); _balance = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _token, 0, abi.encodeWithSignature("approve(address,uint256)", _gauge, 0) ); crvLocker.execute( _token, 0, abi.encodeWithSignature( "approve(address,uint256)", _gauge, _balance ) ); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("deposit(uint256)", _balance) ); } function harvest(address _gauge) external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.execute( mintr, 0, abi.encodeWithSignature("mint(address)", _gauge) ); uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( crv, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } function claimRewards() external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(snx).balanceOf(address(crvLocker)); crvLocker.execute(scrvGauge, 0, abi.encodeWithSignature("claim_rewards()")); uint256 _after = IERC20(snx).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( snx, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } } abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees - start with 4.5% uint256 public performanceTreasuryFee = 450; uint256 public constant performanceTreasuryMax = 10000; uint256 public performanceDevFee = 0; uint256 public constant performanceDevMax = 10000; // Withdrawal fee 0.5% // - 0.325% to treasury // - 0.175% to dev fund uint256 public withdrawalTreasuryFee = 325; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 175; uint256 public constant withdrawalDevFundMax = 100000; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock ) public { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function setWithdrawalDevFundFee(uint256 _withdrawalDevFundFee) external { require(msg.sender == timelock, "!timelock"); withdrawalDevFundFee = _withdrawalDevFundFee; } function setWithdrawalTreasuryFee(uint256 _withdrawalTreasuryFee) external { require(msg.sender == timelock, "!timelock"); withdrawalTreasuryFee = _withdrawalTreasuryFee; } function setPerformanceDevFee(uint256 _performanceDevFee) external { require(msg.sender == timelock, "!timelock"); performanceDevFee = _performanceDevFee; } function setPerformanceTreasuryFee(uint256 _performanceTreasuryFee) external { require(msg.sender == timelock, "!timelock"); performanceTreasuryFee = _performanceTreasuryFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a jar withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div( withdrawalDevFundMax ); IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div( withdrawalTreasuryMax ); IERC20(want).safeTransfer( IController(controller).treasury(), _feeTreasury ); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw funds, used to swap between strategies function withdrawForSwap(uint256 _amount) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawSome(_amount); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); IERC20(want).safeTransfer(_jar, balance); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest() public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _distributePerformanceFeesAndDeposit() internal { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Treasury fees IERC20(want).safeTransfer( IController(controller).treasury(), _want.mul(performanceTreasuryFee).div(performanceTreasuryMax) ); // Performance fee IERC20(want).safeTransfer( IController(controller).devfund(), _want.mul(performanceDevFee).div(performanceDevMax) ); deposit(); } } } abstract contract StrategyCurveBase is StrategyBase { // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { curve = _curve; gauge = _gauge; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return ICurveGauge(gauge).balanceOf(address(this)); } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(address(this)); } function getMostPremium() public virtual view returns (address, uint256); // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(gauge, 0); IERC20(want).safeApprove(gauge, _want); ICurveGauge(gauge).deposit(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ICurveGauge(gauge).withdraw(_amount); return _amount; } } abstract contract StrategyStakingRewardsBase is StrategyBase { address public rewards; // **** Getters **** constructor( address _rewards, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { rewards = _rewards; } function balanceOfPool() public override view returns (uint256) { return IStakingRewards(rewards).balanceOf(address(this)); } function getHarvestable() external view returns (uint256) { return IStakingRewards(rewards).earned(address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).safeApprove(rewards, _want); IStakingRewards(rewards).stake(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IStakingRewards(rewards).withdraw(_amount); return _amount; } } abstract contract StrategyUniFarmBase is StrategyStakingRewardsBase { // Token addresses address public uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; // WETH/<token1> pair address public token1; // How much UNI tokens to keep? uint256 public keepUNI = 0; uint256 public constant keepUNIMax = 10000; constructor( address _token1, address _rewards, address _lp, address _governance, address _strategist, address _controller, address _timelock ) public StrategyStakingRewardsBase( _rewards, _lp, _governance, _strategist, _controller, _timelock ) { token1 = _token1; } // **** Setters **** function setKeepUNI(uint256 _keepUNI) external { require(msg.sender == timelock, "!timelock"); keepUNI = _keepUNI; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // Collects UNI tokens IStakingRewards(rewards).getReward(); uint256 _uni = IERC20(uni).balanceOf(address(this)); if (_uni > 0) { // 10% is locked up for future gov uint256 _keepUNI = _uni.mul(keepUNI).div(keepUNIMax); IERC20(uni).safeTransfer( IController(controller).treasury(), _keepUNI ); _swapUniswap(uni, weth, _uni.sub(_keepUNI)); } // Swap half WETH for DAI uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapUniswap(weth, token1, _weth.div(2)); } // Adds in liquidity for ETH/DAI _weth = IERC20(weth).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_weth > 0 && _token1 > 0) { IERC20(weth).safeApprove(univ2Router2, 0); IERC20(weth).safeApprove(univ2Router2, _weth); IERC20(token1).safeApprove(univ2Router2, 0); IERC20(token1).safeApprove(univ2Router2, _token1); UniswapRouterV2(univ2Router2).addLiquidity( weth, token1, _weth, _token1, 0, 0, address(this), now + 60 ); // Donates DUST IERC20(weth).transfer( IController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(token1).safeTransfer( IController(controller).treasury(), IERC20(token1).balanceOf(address(this)) ); } // We want to get back UNI LP tokens _distributePerformanceFeesAndDeposit(); } } contract StrategyUniEthDaiLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711; address public uni_eth_dai_lp = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( dai, uni_rewards, uni_eth_dai_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthDaiLpV4"; } } contract StrategyUniEthUsdcLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x7FBa4B8Dc5E7616e59622806932DBea72537A56b; address public uni_eth_usdc_lp = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdc, uni_rewards, uni_eth_usdc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdcLpV4"; } } contract StrategyUniEthUsdtLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x6C3e4cb2E96B01F4b866965A91ed4437839A121a; address public uni_eth_usdt_lp = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdt, uni_rewards, uni_eth_usdt_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdtLpV4"; } } contract StrategyUniEthWBtcLpV2 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xCA35e32e7926b96A9988f61d510E038108d8068e; address public uni_eth_wbtc_lp = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( wbtc, uni_rewards, uni_eth_wbtc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthWBtcLpV2"; } } interface Hevm { function warp(uint256) external; function roll(uint x) external; function store(address c, bytes32 loc, bytes32 val) external; } contract MockERC20 is ERC20 { constructor(string memory name, string memory symbol) public ERC20(name, symbol) {} function mint(address recipient, uint256 amount) public { _mint(recipient, amount); } } contract DSTest { event eventListener (address target, bool exact); event logs (bytes); event log_bytes32 (bytes32); event log_named_address (bytes32 key, address val); event log_named_bytes32 (bytes32 key, bytes32 val); event log_named_decimal_int (bytes32 key, int val, uint decimals); event log_named_decimal_uint (bytes32 key, uint val, uint decimals); event log_named_int (bytes32 key, int val); event log_named_uint (bytes32 key, uint val); event log_named_string (bytes32 key, string val); bool public IS_TEST; bool public failed; constructor() internal { IS_TEST = true; } function fail() internal { failed = true; } function expectEventsExact(address target) internal { emit eventListener(target, true); } modifier logs_gas() { uint startGas = gasleft(); _; uint endGas = gasleft(); emit log_named_uint("gas", startGas - endGas); } function assertTrue(bool condition) internal { if (!condition) { emit log_bytes32("Assertion failed"); fail(); } } function assertEq(address a, address b) internal { if (a != b) { emit log_bytes32("Error: Wrong `address' value"); emit log_named_address(" Expected", b); emit log_named_address(" Actual", a); fail(); } } function assertEq32(bytes32 a, bytes32 b) internal { assertEq(a, b); } function assertEq(bytes32 a, bytes32 b) internal { if (a != b) { emit log_bytes32("Error: Wrong `bytes32' value"); emit log_named_bytes32(" Expected", b); emit log_named_bytes32(" Actual", a); fail(); } } function assertEqDecimal(int a, int b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_int(" Expected", b, decimals); emit log_named_decimal_int(" Actual", a, decimals); fail(); } } function assertEqDecimal(uint a, uint b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_uint(" Expected", b, decimals); emit log_named_decimal_uint(" Actual", a, decimals); fail(); } } function assertEq(int a, int b) internal { if (a != b) { emit log_bytes32("Error: Wrong `int' value"); emit log_named_int(" Expected", b); emit log_named_int(" Actual", a); fail(); } } function assertEq(uint a, uint b) internal { if (a != b) { emit log_bytes32("Error: Wrong `uint' value"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEq(string memory a, string memory b) internal { if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { emit log_bytes32("Error: Wrong `string' value"); emit log_named_string(" Expected", b); emit log_named_string(" Actual", a); fail(); } } function assertEq0(bytes memory a, bytes memory b) internal { bool ok = true; if (a.length == b.length) { for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) { ok = false; } } } else { ok = false; } if (!ok) { emit log_bytes32("Error: Wrong `bytes' value"); emit log_named_bytes32(" Expected", "[cannot show `bytes' value]"); emit log_named_bytes32(" Actual", "[cannot show `bytes' value]"); fail(); } } } contract User { function execute( address target, uint256 value, string memory signature, bytes memory data ) public payable returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked( bytes4(keccak256(bytes(signature))), data ); } (bool success, bytes memory returnData) = target.call{value: value}( callData ); require(success, "!user-execute"); return returnData; } } contract StakngRewardsTest is DSTest { using SafeMath for uint256; MockERC20 stakingToken; MockERC20 rewardsToken; StakingRewards stakingRewards; address owner; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); function setUp() public { owner = address(this); stakingToken = new MockERC20("staking", "STAKE"); rewardsToken = new MockERC20("rewards", "RWD"); stakingRewards = new StakingRewards( owner, address(rewardsToken), address(stakingToken) ); } function test_staking() public { uint256 stakeAmount = 100 ether; uint256 rewardAmount = 100 ether; stakingToken.mint(owner, stakeAmount); rewardsToken.mint(owner, rewardAmount); stakingToken.approve(address(stakingRewards), stakeAmount); stakingRewards.stake(stakeAmount); // // Make sure nothing is earned uint256 _before = stakingRewards.earned(owner); assertEq(_before, 0); // Fast forward hevm.warp(block.timestamp + 1 days); // No funds until we actually supply funds uint256 _after = stakingRewards.earned(owner); assertEq(_after, _before); // Give rewards rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateBefore = stakingRewards.getRewardForDuration(); assertTrue(_rateBefore > 0); // Fast forward _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); assertTrue(_after > _before); assertTrue(_after > 0); // Add more rewards, rate should increase rewardsToken.mint(owner, rewardAmount); rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateAfter = stakingRewards.getRewardForDuration(); assertTrue(_rateAfter > _rateBefore); // Warp to period finish hevm.warp(stakingRewards.periodFinish() + 1 days); // Retrieve tokens stakingRewards.getReward(); _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); // Earn 0 after period finished assertEq(_before, 0); assertEq(_after, 0); } } contract UniCurveConverter { using SafeMath for uint256; using SafeERC20 for IERC20; UniswapRouterV2 public router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Stablecoins address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // Wrapped stablecoins address public constant scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Weth address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // susd v2 pool ICurveFi_4 public curve = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); // UNI LP -> Curve LP // Assume th function convert(address _lp, uint256 _amount) public { // Get LP Tokens IERC20(_lp).safeTransferFrom(msg.sender, address(this), _amount); // Get Uniswap pair IUniswapV2Pair fromPair = IUniswapV2Pair(_lp); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } // Remove liquidity IERC20(_lp).safeApprove(address(router), 0); IERC20(_lp).safeApprove(address(router), _amount); router.removeLiquidity( fromPair.token0(), fromPair.token1(), _amount, 0, 0, address(this), now + 60 ); // Most premium stablecoin (address premiumStablecoin, ) = getMostPremium(); // Convert weth -> most premium stablecoin address[] memory path = new address[](2); path[0] = weth; path[1] = premiumStablecoin; IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(weth).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Convert the other asset into stablecoin if its not a stablecoin address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); if (_from != dai && _from != usdc && _from != usdt && _from != susd) { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = premiumStablecoin; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); } // Add liquidity to curve IERC20(dai).safeApprove(address(curve), 0); IERC20(dai).safeApprove(address(curve), uint256(-1)); IERC20(usdc).safeApprove(address(curve), 0); IERC20(usdc).safeApprove(address(curve), uint256(-1)); IERC20(usdt).safeApprove(address(curve), 0); IERC20(usdt).safeApprove(address(curve), uint256(-1)); IERC20(susd).safeApprove(address(curve), 0); IERC20(susd).safeApprove(address(curve), uint256(-1)); curve.add_liquidity( [ IERC20(dai).balanceOf(address(this)), IERC20(usdc).balanceOf(address(this)), IERC20(usdt).balanceOf(address(this)), IERC20(susd).balanceOf(address(this)) ], 0 ); // Sends token back to user IERC20(scrv).transfer( msg.sender, IERC20(scrv).balanceOf(address(this)) ); } function getMostPremium() public view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface MasterChef { function userInfo(uint256, address) external view returns (uint256, uint256); } contract PickleVoteProxy { // ETH/PICKLE token IERC20 public constant votes = IERC20( 0xdc98556Ce24f007A5eF6dC1CE96322d65832A819 ); // Pickle's masterchef contract MasterChef public constant chef = MasterChef( 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d ); // Pool 0 is the ETH/PICKLE pool uint256 public constant pool = uint256(0); // Using 9 decimals as we're square rooting the votes function decimals() external pure returns (uint8) { return uint8(9); } function name() external pure returns (string memory) { return "PICKLEs In The Citadel"; } function symbol() external pure returns (string memory) { return "PICKLE C"; } function totalSupply() external view returns (uint256) { return sqrt(votes.totalSupply()); } function balanceOf(address _voter) external view returns (uint256) { (uint256 _votes, ) = chef.userInfo(pool, _voter); return sqrt(_votes); } function sqrt(uint256 x) public pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } constructor() public {} } contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PICKLEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPicklePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPicklePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. PICKLEs to distribute per block. uint256 lastRewardBlock; // Last block number that PICKLEs distribution occurs. uint256 accPicklePerShare; // Accumulated PICKLEs per share, times 1e12. See below. } // The PICKLE TOKEN! PickleToken public pickle; // Dev fund (2%, initially) uint256 public devFundDivRate = 50; // Dev address. address public devaddr; // Block number when bonus PICKLE period ends. uint256 public bonusEndBlock; // PICKLE tokens created per block. uint256 public picklePerBlock; // Bonus muliplier for early pickle makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PICKLE mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( PickleToken _pickle, address _devaddr, uint256 _picklePerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { pickle = _pickle; devaddr = _devaddr; picklePerBlock = _picklePerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPicklePerShare: 0 }) ); } // Update the given pool's PICKLE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending PICKLEs on frontend. function pendingPickle(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPicklePerShare = pool.accPicklePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accPicklePerShare = accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accPicklePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); pickle.mint(devaddr, pickleReward.div(devFundDivRate)); pickle.mint(address(this), pickleReward); pool.accPicklePerShare = pool.accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for PICKLE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accPicklePerShare) .div(1e12) .sub(user.rewardDebt); safePickleTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accPicklePerShare).div(1e12).sub( user.rewardDebt ); safePickleTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe pickle transfer function, just in case if rounding error causes pool to not have enough PICKLEs. function safePickleTransfer(address _to, uint256 _amount) internal { uint256 pickleBal = pickle.balanceOf(address(this)); if (_amount > pickleBal) { pickle.transfer(_to, pickleBal); } else { pickle.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // **** Additional functions separate from the original masterchef contract **** function setPicklePerBlock(uint256 _picklePerBlock) public onlyOwner { require(_picklePerBlock > 0, "!picklePerBlock-0"); picklePerBlock = _picklePerBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner { require(_devFundDivRate > 0, "!devFundDivRate-0"); devFundDivRate = _devFundDivRate; } } contract PickleToken is ERC20("PickleToken", "PICKLE"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } interface IJar is IERC20 { function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function earn() external; function decimals() external view returns (uint8); } contract StrategyCmpdDaiV2 is StrategyBase, Exponential { address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; // Require a 0.1 buffer between // market collateral factor and strategy's collateral factor // when leveraging uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000; // Allow a 0.05 buffer // between market collateral factor and strategy's collateral factor // until we have to deleverage // This is so we can hit max leverage and keep accruing interest uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; // Keeper bots // Maintain leverage within buffer mapping(address => bool) keepers; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(dai, _governance, _strategist, _controller, _timelock) { // Enter cDAI Market address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).enterMarkets(ctokens); } // **** Modifiers **** // modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } // **** Views **** // function getName() external override pure returns (string memory) { return "StrategyCmpdDaiV2"; } function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cdai) .getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate( Exp({mantissa: exchangeRate}), cTokenBal ); return bal; } function getBorrowedView() public view returns (uint256) { return ICToken(cdai).borrowBalanceStored(address(this)); } function balanceOfPool() public override view returns (uint256) { uint256 supplied = getSuppliedView(); uint256 borrowed = getBorrowedView(); return supplied.sub(borrowed); } // Given an unleveraged supply balance, return the target // leveraged supply balance which is still within the safety buffer function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax) ); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax) ); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); return colFactor; } // Max leverage we can go up to, w.r.t safe buffer function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); // Infinite geometric series uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } // **** Pseudo-view functions (use `callStatic` on these) **** // /* The reason why these exists is because of the nature of the interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. */ function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt( comp, comptroller, address(this) ); return accrued; } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cdai).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cdai).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); // 99.99% just in case some dust accumulates return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div( 10000 ); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } // **** Setters **** // function addKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = true; } function removeKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = false; } function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorSyncBuffer = _colFactorSyncBuffer; } // **** State mutations **** // // Do a `callStatic` on this. // If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call) function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); // If we're not safe if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function leverageToMax() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); leverageUntil(idealSupply); } // Leverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function leverageUntil(uint256 _supplyAmount) public onlyKeepers { // 1. Borrow out <X> DAI // 2. Supply <X> DAI uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); // Since we're only leveraging one asset // Supplied = borrowed uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cdai).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function deleverageToMin() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); deleverageUntil(unleveragedSupply); } // Deleverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); // Since we're only leveraging on 1 asset // redeemable = borrowable uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } _distributePerformanceFeesAndDeposit(); } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cdai, 0); IERC20(want).safeApprove(cdai, _want); require(ICToken(cdai).mint(_want) == 0, "!deposit"); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); // Make sure market can cover liquidity require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); // How much borrowed amount do we need to free? uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); // If the amount we need to free is > borrowed // Just free up all the borrowed amount if (borrowedToBeFree > borrowed) { this.deleverageToMin(); } else { // Otherwise just keep freeing up borrowed amounts until // we hit a safe number to redeem our underlying this.deleverageUntil(supplied.sub(borrowedToBeFree)); } // Redeems underlying require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } } contract StrategyCurve3CRVv2 is StrategyCurveBase { // Curve stuff address public three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public three_gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; address public three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( three_pool, three_gauge, three_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_3(curve).balances(0); // DAI balances[1] = ICurveFi_3(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_3(curve).balances(2).mul(10**12); // USDT // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] ) { return (usdt, 2); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurve3CRVv2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[3] memory liquidity; liquidity[toIndex] = _to; ICurveFi_3(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveRenCRVv2 is StrategyCurveBase { // https://www.curve.fi/ren // Curve stuff address public ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address public ren_gauge = 0xB1F2cdeC61db658F091671F5f199635aEF202CAC; address public ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( ren_pool, ren_gauge, ren_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { // Both 8 decimals, so doesn't matter uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_2(curve).balances(0); // RENBTC balances[1] = ICurveFi_2(curve).balances(1); // WBTC // renbtc if (balances[0] < balances[1]) { return (renbtc, 0); } // WBTC if (balances[1] < balances[0]) { return (wbtc, 1); } // If they're somehow equal, we just want RENBTC return (renbtc, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveRenCRVv2"; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[2] memory liquidity; liquidity[toIndex] = _to; ICurveFi_2(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv3_2 is StrategyCurveBase { // Curve stuff address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Harvesting address public snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( susdv2_pool, susdv2_gauge, scrv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv3_2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens ICurveGauge(gauge).claim_rewards(address(this)); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv4_1 is StrategyBase { // Curve address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // tokens we're farming address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // How much CRV tokens to keep uint256 public keepCRV = 500; uint256 public keepCRVMax = 10000; // crv-locker and voter address public scrvVoter; address public crvLocker; constructor( address _scrvVoter, address _crvLocker, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(scrv, _governance, _strategist, _controller, _timelock) { curve = susdv2_pool; gauge = susdv2_gauge; scrvVoter = _scrvVoter; crvLocker = _crvLocker; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return SCRVVoter(scrvVoter).balanceOf(gauge); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv4_1"; } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(crvLocker); } function getMostPremium() public view returns (address, uint8) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutations **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeTransfer(scrvVoter, _want); SCRVVoter(scrvVoter).deposit(gauge, want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { return SCRVVoter(scrvVoter).withdraw(gauge, want, _amount); } function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun / sandwiched // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned/sandwiched? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 SCRVVoter(scrvVoter).harvest(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // How much CRV to keep to restake? uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); IERC20(crv).safeTransfer(address(crvLocker), _keepCRV); // How much CRV to swap? _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens SCRVVoter(scrvVoter).claimRewards(); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract DSTestApprox is DSTest { function assertEqApprox(uint256 a, uint256 b) internal { if (a == 0 && b == 0) { return; } // +/- 5% uint256 bMax = (b * 105) / 100; uint256 bMin = (b * 95) / 100; if (!(a > bMin && a < bMax)) { emit log_bytes32("Error: Wrong `a-uint` value!"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEqVerbose(bool a, bytes memory b) internal { if (!a) { emit log_bytes32("Error: assertion error!"); emit logs(b); fail(); } } } contract DSTestDefiBase is DSTestApprox { using SafeERC20 for IERC20; using SafeMath for uint256; address pickle = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; address burn = 0x000000000000000000000000000000000000dEaD; address susdv2_deposit = 0xFCBa3E75865d2d561BE8D220616520c171F12851; address susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; address eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; address uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; address wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); UniswapRouterV2 univ2 = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); IUniswapV2Factory univ2Factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); ICurveFi_4 curveSusdV2 = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); uint256 startTime = block.timestamp; receive() external payable {} fallback () external payable {} function _swap( address _from, address _to, uint256 _amount ) internal { address[] memory path; if (_from == eth || _from == weth) { path = new address[](2); path[0] = weth; path[1] = _to; univ2.swapExactETHForTokens{value: _amount}( 0, path, address(this), now + 60 ); } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(univ2), 0); IERC20(_from).safeApprove(address(univ2), _amount); univ2.swapExactTokensForTokens( _amount, 0, path, address(this), now + 60 ); } } function _getERC20(address token, uint256 _amount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; uint256[] memory ins = univ2.getAmountsIn(_amount, path); uint256 ethAmount = ins[0]; univ2.swapETHForExactTokens{value: ethAmount}( _amount, path, address(this), now + 60 ); } function _getERC20WithETH(address token, uint256 _ethAmount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; univ2.swapExactETHForTokens{value: _ethAmount}( 0, path, address(this), now + 60 ); } function _getUniV2LPToken(address lpToken, uint256 _ethAmount) internal { address token0 = IUniswapV2Pair(lpToken).token0(); address token1 = IUniswapV2Pair(lpToken).token1(); if (token0 != weth) { _getERC20WithETH(token0, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } if (token1 != weth) { _getERC20WithETH(token1, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } IERC20(token0).safeApprove(address(univ2), uint256(0)); IERC20(token0).safeApprove(address(univ2), uint256(-1)); IERC20(token1).safeApprove(address(univ2), uint256(0)); IERC20(token1).safeApprove(address(univ2), uint256(-1)); univ2.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); } function _getUniV2LPToken( address token0, address token1, uint256 _ethAmount ) internal { _getUniV2LPToken(univ2Factory.getPair(token0, token1), _ethAmount); } function _getFunctionSig(string memory sig) internal pure returns (bytes4) { return bytes4(keccak256(bytes(sig))); } function _getDynamicArray(address payable one) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](1); targets[0] = one; return targets; } function _getDynamicArray(bytes memory one) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](1); data[0] = one; return data; } function _getDynamicArray(address payable one, address payable two) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](2); targets[0] = one; targets[1] = two; return targets; } function _getDynamicArray(bytes memory one, bytes memory two) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](2); data[0] = one; data[1] = two; return data; } function _getDynamicArray( address payable one, address payable two, address payable three ) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](3); targets[0] = one; targets[1] = two; targets[2] = three; return targets; } function _getDynamicArray( bytes memory one, bytes memory two, bytes memory three ) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](3); data[0] = one; data[1] = two; data[2] = three; return data; } } contract StrategyCurveFarmTestBase is DSTestDefiBase { address governance; address strategist; address timelock; address devfund; address treasury; address want; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; // **** Tests **** function _test_withdraw() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract StrategyUniFarmTestBase is DSTestDefiBase { address want; address token1; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; function _getWant(uint256 ethAmount, uint256 amount) internal { _getERC20(token1, amount); uint256 _token1 = IERC20(token1).balanceOf(address(this)); IERC20(token1).safeApprove(address(univ2), 0); IERC20(token1).safeApprove(address(univ2), _token1); univ2.addLiquidityETH{value: ethAmount}( token1, _token1, 0, 0, address(this), now + 60 ); } // **** Tests **** function _test_timelock() internal { assertTrue(strategy.timelock() == timelock); strategy.setTimelock(address(1)); assertTrue(strategy.timelock() == address(1)); } function _test_withdraw_release() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Checking withdraw uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Check if we gained interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract PickleSwapTest is DSTestDefiBase { PickleSwap pickleSwap; function setUp() public { pickleSwap = new PickleSwap(); } function _test_uni_lp_swap(address lp1, address lp2) internal { _getUniV2LPToken(lp1, 20 ether); uint256 _balance = IERC20(lp1).balanceOf(address(this)); uint256 _before = IERC20(lp2).balanceOf(address(this)); IERC20(lp1).safeIncreaseAllowance(address(pickleSwap), _balance); pickleSwap.convertWETHPair(lp1, lp2, _balance); uint256 _after = IERC20(lp2).balanceOf(address(this)); assertTrue(_after > _before); assertTrue(_after > 0); } function test_pickleswap_dai_usdc() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdc) ); } function test_pickleswap_dai_usdt() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdt) ); } function test_pickleswap_usdt_susd() public { _test_uni_lp_swap( univ2Factory.getPair(weth, usdt), univ2Factory.getPair(weth, susd) ); } } contract StrategyCmpndDaiV1 is DSTestDefiBase { StrategyCmpdDaiV2 strategy; ControllerV4 controller; PickleJar pickleJar; address governance; address strategist; address timelock; address devfund; address treasury; address want; function setUp() public { want = dai; governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = new StrategyCmpdDaiV2( governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); } function testFail_cmpnd_dai_v1_onlyKeeper_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); User randomUser = new User(); randomUser.execute(address(strategy), 0, "leverageToMax()", ""); } function testFail_cmpnd_dai_v1_onlyKeeper_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); strategy.leverageToMax(); User randomUser = new User(); randomUser.execute(address(strategy), 0, "deleverageToMin()", ""); } function test_cmpnd_dai_v1_comp_accrued() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 compAccrued = strategy.getCompAccrued(); assertEq(compAccrued, 0); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day compAccrued = strategy.getCompAccrued(); assertTrue(compAccrued > 0); } function test_cmpnd_dai_v1_comp_sync() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Sets colFactor Buffer to be 3% (safeSync is 5%) strategy.setColFactorLeverageBuffer(30); strategy.leverageToMax(); // Back to 10% strategy.setColFactorLeverageBuffer(100); uint256 colFactor = strategy.getColFactor(); uint256 safeColFactor = strategy.getSafeLeverageColFactor(); assertTrue(colFactor > safeColFactor); // Sync automatically fixes the colFactor for us bool shouldSync = strategy.sync(); assertTrue(shouldSync); colFactor = strategy.getColFactor(); assertEqApprox(colFactor, safeColFactor); shouldSync = strategy.sync(); assertTrue(!shouldSync); } function test_cmpnd_dai_v1_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 _stratInitialBal = strategy.balanceOf(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.leverageToMax(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); uint256 _safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertTrue(_afterCR > _beforeCR); assertTrue(_afterLev > _beforeLev); assertEqApprox(_safeLeverageColFactor, _afterCR); uint256 _maxLeverage = strategy.getMaxLeverage(); assertTrue(_maxLeverage > 2e18); // Should be ~2.6, depending on colFactorLeverageBuffer uint256 leverageTarget = strategy.getLeveragedSupplyTarget( _stratInitialBal ); uint256 leverageSupplied = strategy.getSupplied(); assertEqApprox( leverageSupplied, _stratInitialBal.mul(_maxLeverage).div(1e18) ); assertEqApprox(leverageSupplied, leverageTarget); uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); assertEqApprox(unleveragedSupplied, _stratInitialBal); } function test_cmpnd_dai_v1_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.deleverageToMin(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); assertTrue(_afterCR < _beforeCR); assertTrue(_afterLev < _beforeLev); assertEq(0, _afterCR); // 0 since we're not borrowing anything uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); uint256 supplied = strategy.getSupplied(); assertEqApprox(unleveragedSupplied, supplied); } function test_cmpnd_dai_v1_withdrawSome() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(25e18); uint256 _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 25e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(10e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 10e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(30e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 30e18); // Make sure we're still leveraging uint256 _leverage = strategy.getCurrentLeverage(); assertTrue(_leverage > 1e18); } function test_cmpnd_dai_v1_withdrawAll() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function test_cmpnd_dai_v1_earn_harvest_rewards() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day // Call the harvest function uint256 _before = strategy.getSupplied(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = strategy.getSupplied(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } function test_cmpnd_dai_v1_functions() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 initialSupplied = strategy.getSupplied(); uint256 initialBorrowed = strategy.getBorrowed(); uint256 initialBorrowable = strategy.getBorrowable(); uint256 marketColFactor = strategy.getMarketColFactor(); uint256 maxLeverage = strategy.getMaxLeverage(); // Earn deposits 95% into strategy assertEqApprox(initialSupplied, 95e18); assertEqApprox( initialBorrowable, initialSupplied.mul(marketColFactor).div(1e18) ); assertEqApprox(initialBorrowed, 0); // Leverage to Max strategy.leverageToMax(); uint256 supplied = strategy.getSupplied(); uint256 borrowed = strategy.getBorrowed(); uint256 borrowable = strategy.getBorrowable(); uint256 currentColFactor = strategy.getColFactor(); uint256 safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertEqApprox(supplied, initialSupplied.mul(maxLeverage).div(1e18)); assertEqApprox(borrowed, supplied.mul(safeLeverageColFactor).div(1e18)); assertEqApprox( borrowable, supplied.mul(marketColFactor.sub(currentColFactor)).div(1e18) ); assertEqApprox(currentColFactor, safeLeverageColFactor); assertTrue(marketColFactor > currentColFactor); assertTrue(marketColFactor > safeLeverageColFactor); // Deleverage strategy.deleverageToMin(); uint256 deleverageSupplied = strategy.getSupplied(); uint256 deleverageBorrowed = strategy.getBorrowed(); uint256 deleverageBorrowable = strategy.getBorrowable(); assertEqApprox(deleverageSupplied, initialSupplied); assertEqApprox(deleverageBorrowed, initialBorrowed); assertEqApprox(deleverageBorrowable, initialBorrowable); } function test_cmpnd_dai_v1_deleverage_stepping() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); strategy.deleverageUntil(200e18); uint256 supplied = strategy.getSupplied(); assertEqApprox(supplied, 200e18); strategy.deleverageUntil(180e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 180e18); strategy.deleverageUntil(120e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 120e18); } } contract StrategyCurve3CRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = three_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[3] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(three_pool, liquidity[0]); ICurveFi_3(three_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_3crv_v1_withdraw() public { _test_withdraw(); } function test_3crv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveRenCRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = ren_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10e8); // 10 wbtc } function _getWant(uint256 btcAmount) internal { _getERC20(wbtc, btcAmount); uint256[2] memory liquidity; liquidity[1] = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(ren_pool, liquidity[1]); ICurveFi_2(ren_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_rencrv_v1_withdraw() public { _test_withdraw(); } function test_rencrv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv3_2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = scrv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_scrv_v3_1_withdraw() public { _test_withdraw(); } function test_scrv_v3_1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv4Test is DSTestDefiBase { address escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address curveSmartContractChecker = 0xca719728Ef172d0961768581fdF35CB116e0B7a4; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; StrategyCurveSCRVv4_1 strategy; SCRVVoter scrvVoter; CRVLocker crvLocker; function setUp() public { governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); crvLocker = new CRVLocker(governance); scrvVoter = new SCRVVoter(governance, address(crvLocker)); strategy = new StrategyCurveSCRVv4_1( address(scrvVoter), address(crvLocker), governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); scrvVoter.approveStrategy(address(strategy)); scrvVoter.approveStrategy(governance); crvLocker.addVoter(address(scrvVoter)); hevm.warp(startTime); // Approve our strategy on smartContractWhitelist // Modify storage value so we are approved by the smart-wallet-white-list // storage in solidity - https://ethereum.stackexchange.com/a/41304 bytes32 key = bytes32(uint256(address(crvLocker))); bytes32 pos = bytes32(0); // pos 0 as its the first state variable bytes32 loc = keccak256(abi.encodePacked(key, pos)); hevm.store(curveSmartContractChecker, loc, bytes32(uint256(1))); // Make sure our crvLocker is whitelisted assertTrue( ICurveSmartContractChecker(curveSmartContractChecker).wallets( address(crvLocker) ) ); } function _getSCRV(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** function test_scrv_v4_1_withdraw() public { _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(scrv).balanceOf(address(pickleJar)); controller.withdrawAll(scrv); uint256 _after = IERC20(scrv).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(scrv).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(scrv).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _scrv); } function test_scrv_v4_1_get_earn_harvest_rewards() public { address dev = controller.devfund(); // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _rewardsBefore = IERC20(scrv).balanceOf(treasury); User(strategist).execute(address(strategy), 0, "harvest()", ""); uint256 _after = pickleJar.balance(); uint256 _rewardsAfter = IERC20(scrv).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _rewardsAfter.sub(_rewardsBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(scrv).balanceOf(dev); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(scrv).balanceOf(dev); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); } function test_scrv_v4_1_lock() public { // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); // Call the harvest function strategy.harvest(); // Make sure we can open lock uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); // Create a lock crvLocker.createLock(_after, block.timestamp + 5 weeks); // Harvest etc hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Increase amount crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); // Increase unlockTime crvLocker.increaseUnlockTime(block.timestamp + 5 weeks); // Fast forward hevm.warp(block.timestamp + 5 weeks + 1 hours); // Withdraw _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.release(); _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); } } contract StrategyUniEthDaiLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; token1 = dai; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethdaiv3_1_timelock() public { _test_timelock(); } function test_ethdaiv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethdaiv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdcLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; token1 = usdc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdcv3_1_timelock() public { _test_timelock(); } function test_ethusdcv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdcv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdtLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; token1 = usdt; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdtv3_1_timelock() public { _test_timelock(); } function test_ethusdtv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdtv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthWBtcLpV2Test is StrategyUniFarmTestBase { function setUp() public { want = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; token1 = wbtc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethwbtcv1_timelock() public { _test_timelock(); } function test_ethwbtcv1_withdraw_release() public { _test_withdraw_release(); } function test_ethwbtcv1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract UniCurveConverterTest is DSTestDefiBase { UniCurveConverter uniCurveConverter; function setUp() public { uniCurveConverter = new UniCurveConverter(); } function _test_uni_curve_converter(address token0, address token1) internal { address lp = univ2Factory.getPair(token0, token1); _getUniV2LPToken(lp, 100 ether); uint256 _balance = IERC20(lp).balanceOf(address(this)); IERC20(lp).safeApprove(address(uniCurveConverter), 0); IERC20(lp).safeApprove(address(uniCurveConverter), uint256(-1)); uint256 _before = IERC20(scrv).balanceOf(address(this)); uniCurveConverter.convert(lp, _balance); uint256 _after = IERC20(scrv).balanceOf(address(this)); // Gets scrv assertTrue(_after > _before); assertTrue(_after > 0); // No token left behind in router assertEq(IERC20(token0).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(token1).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(weth).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(dai).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdc).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdt).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(susd).balanceOf(address(uniCurveConverter)), 0); } function test_uni_curve_convert_dai_weth() public { _test_uni_curve_converter(dai, weth); } function test_uni_curve_convert_usdt_weth() public { _test_uni_curve_converter(usdt, weth); } function test_uni_curve_convert_wbtc_weth() public { _test_uni_curve_converter(wbtc, weth); } } contract StrategyCurveCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; PickleJar[] curvePickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } // **** Internal functions **** // // Theres so many internal functions due to stack blowing up // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _get_uniswap_pl_swap_data(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature("swapUniswap(address,address)", from, to); } function _test_curve_curve( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) public { // Get LP _getCurveLP(curvePools[fromIndex], amount); // Deposit into pickle jars address from = address(curvePickleJars[fromIndex].token()); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Approve controller uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Swap try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-receive-amount"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_curve_curve_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); uint256 toCurvePoolSize = 4; uint256 toCurveUnderlyingIndex = 0; address toCurveUnderlying = dai; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; address payable target0 = payable(address(curveProxyLogic)); bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Add liquidity address toCurve = curvePools[toIndex]; address payable target1 = payable(address(curveProxyLogic)); bytes memory data1 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); // Swap _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray(target0, target1), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_curve_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); uint256 toCurvePoolSize = 2; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = wbtc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(dai, toCurveUnderlying); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_2() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 2; address toCurveUnderlying = usdt; // Remove liquidity address fromCurve = susdv2_deposit; // curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdc, usdt); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_3() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 4e6; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(wbtc, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_4() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 2; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = susdv2_deposit; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdt, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } } contract StrategyCurveUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } function _get_primitive_to_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "primitiveToLpTokens(address,address,address)", from, to, dustRecipient ); } function _get_curve_remove_liquidity_data( address curve, address curveLP, int128 index ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", curve, curveLP, index ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IUniswapV2Pair token1 = IUniswapV2Pair( address(uniPickleJars[toIndex].token()) ); uint256 MAX_DUST = 1000; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Curve -> UNI LP should be optimal supply // Note: We refund the access, which is why its checking this balance assertTrue(IERC20(token1.token0()).balanceOf(address(this)) < MAX_DUST); assertTrue(IERC20(token1.token1()).balanceOf(address(this)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_curve_uni_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(curvePickleJars[fromIndex].token()); _getCurveLP(curvePools[fromIndex], amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_curve_uni_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = usdc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_3() public { uint256 fromIndex = 0; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_3() public { uint256 fromIndex = 1; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_2_3() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 4e6; address fromUnderlying = wbtc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_uniswap_remove_liquidity_data(address pair) internal pure returns (bytes memory) { return abi.encodeWithSignature("removeLiquidity(address)", pair); } function _get_uniswap_lp_tokens_to_primitive(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature( "lpTokensToPrimitive(address,address)", from, to ); } function _get_curve_add_liquidity_data( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", curve, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, underlying ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertEq(token0.balanceOf(address(controller)), 0); assertEq(token1.balanceOf(address(controller)), 0); assertEq(IERC20(wbtc).balanceOf(address(controller)), 0); // assertEq(IERC20(usdt).balanceOf(address(controller)), 0); // assertEq(IERC20(usdc).balanceOf(address(controller)), 0); // assertEq(IERC20(susd).balanceOf(address(controller)), 0); // assertEq(IERC20(dai).balanceOf(address(controller)), 0); // No balance left behind! assertEq(token1.balanceOf(address(this)), 0); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_curve_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_uni_curve_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_0() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_0() public { uint256 fromIndex = 3; uint256 toIndex = 0; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_1() public { uint256 fromIndex = 2; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_4_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_2() public { uint256 fromIndex = 2; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_2() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] uniStrategies; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] uniUnderlying; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_swap_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "swapUniLPTokens(address,address,address)", from, to, dustRecipient ); } function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = uniPickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_uni( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_uni_uni_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_2() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_3() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } }
Require a 0.1 buffer between market collateral factor and strategy's collateral factor when leveraging Allow a 0.05 buffer between market collateral factor and strategy's collateral factor until we have to deleverage This is so we can hit max leverage and keep accruing interest Keeper bots Maintain leverage within buffer
contract StrategyCmpdDaiV2 is StrategyBase, Exponential { address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000; uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; mapping(address => bool) keepers; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(dai, _governance, _strategist, _controller, _timelock) { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).enterMarkets(ctokens); } modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } function getName() external override pure returns (string memory) { return "StrategyCmpdDaiV2"; } function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cdai) .getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate( cTokenBal ); return bal; } Exp({mantissa: exchangeRate}), function getBorrowedView() public view returns (uint256) { return ICToken(cdai).borrowBalanceStored(address(this)); } function balanceOfPool() public override view returns (uint256) { uint256 supplied = getSuppliedView(); uint256 borrowed = getBorrowedView(); return supplied.sub(borrowed); } function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); uint256 safeColFactor = colFactor.sub( colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax) ); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); uint256 safeColFactor = colFactor.sub( colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax) ); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); return colFactor; } function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt( comp, comptroller, address(this) ); return accrued; } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cdai).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cdai).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div( 10000 ); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } function addKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = true; } function removeKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = false; } function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorSyncBuffer = _colFactorSyncBuffer; } function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function leverageToMax() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); leverageUntil(idealSupply); } function leverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cdai).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function leverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cdai).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function leverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cdai).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function deleverageToMin() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); deleverageUntil(unleveragedSupply); } function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } _distributePerformanceFeesAndDeposit(); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } _distributePerformanceFeesAndDeposit(); } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cdai, 0); IERC20(want).safeApprove(cdai, _want); require(ICToken(cdai).mint(_want) == 0, "!deposit"); } } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cdai, 0); IERC20(want).safeApprove(cdai, _want); require(ICToken(cdai).mint(_want) == 0, "!deposit"); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); if (borrowedToBeFree > borrowed) { this.deleverageToMin(); this.deleverageUntil(supplied.sub(borrowedToBeFree)); } require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); if (borrowedToBeFree > borrowed) { this.deleverageToMin(); this.deleverageUntil(supplied.sub(borrowedToBeFree)); } require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); if (borrowedToBeFree > borrowed) { this.deleverageToMin(); this.deleverageUntil(supplied.sub(borrowedToBeFree)); } require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } } else { }
7,450,226
[ 1, 8115, 279, 374, 18, 21, 1613, 3086, 13667, 4508, 2045, 287, 5578, 471, 6252, 1807, 4508, 2045, 287, 5578, 1347, 884, 502, 5755, 7852, 279, 374, 18, 6260, 1613, 3086, 13667, 4508, 2045, 287, 5578, 471, 6252, 1807, 4508, 2045, 287, 5578, 3180, 732, 1240, 358, 1464, 73, 5682, 1220, 353, 1427, 732, 848, 6800, 943, 884, 5682, 471, 3455, 4078, 8653, 310, 16513, 1475, 9868, 2512, 87, 490, 1598, 530, 884, 5682, 3470, 1613, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19736, 31832, 72, 40, 10658, 58, 22, 353, 19736, 2171, 16, 29770, 649, 288, 203, 203, 565, 1758, 203, 203, 3639, 1071, 5381, 532, 337, 1539, 273, 374, 92, 23, 72, 10689, 15561, 2163, 37, 6938, 70, 7616, 9498, 70, 5082, 26897, 6564, 70, 41, 22, 8906, 40, 7235, 38, 29, 71, 29, 19728, 23, 38, 31, 203, 203, 565, 1758, 1071, 5381, 26882, 273, 374, 7669, 25, 3437, 72, 23622, 3787, 69, 5082, 8898, 38, 72, 5026, 22, 37, 73, 23, 5608, 70, 24, 70, 29, 71, 3462, 41, 20, 69, 29, 69, 20, 5608, 31, 203, 203, 565, 1758, 1071, 5381, 5248, 77, 273, 374, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 31, 203, 203, 565, 1758, 1071, 5381, 1161, 273, 374, 6511, 713, 73, 11290, 15237, 6028, 22, 39, 4763, 18212, 11149, 41, 26, 74, 10321, 28406, 3461, 26565, 37, 27, 74, 5558, 5482, 28, 31, 203, 203, 565, 1758, 1071, 5381, 276, 2414, 77, 273, 374, 92, 25, 72, 23, 69, 25, 5718, 41, 24, 40, 26, 4331, 40, 26, 22214, 952, 21, 41, 361, 4763, 14509, 70, 2090, 29, 8875, 41, 23, 1105, 23, 31, 203, 203, 565, 1758, 1071, 5381, 276, 2437, 273, 374, 92, 24, 40, 7201, 22, 40, 3657, 5520, 24, 6675, 5558, 40, 3103, 74, 29, 38, 21, 74, 41, 29, 73, 21, 2414, 69, 8642, 2643, 5324, 20, 2056, 25, 31, 2 ]
./partial_match/1/0x10AB4bF822364A71468F428feDab8f615661ae9D/sources/BOS.sol
once enabled, can never be turned off
function bird(uint egg) external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; tradingActiveBlock = block.number; earlyPenaltyBlocks = egg; }
4,001,724
[ 1, 8243, 3696, 16, 848, 5903, 506, 21826, 3397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 324, 6909, 12, 11890, 25144, 13, 3903, 1338, 5541, 288, 203, 3639, 1284, 7459, 3896, 273, 638, 31, 203, 3639, 7720, 1526, 273, 638, 31, 203, 3639, 1142, 48, 84, 38, 321, 950, 273, 1203, 18, 5508, 31, 203, 3639, 1284, 7459, 3896, 1768, 273, 1203, 18, 2696, 31, 203, 3639, 11646, 24251, 15006, 6450, 273, 25144, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-22 */ // Sources flattened with hardhat v2.6.4 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; 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"); (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"); (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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; interface IMonstersBash { function toggleSaleState() external; function saleIsActive() external returns (bool); function MAX_SUPPLY() external view returns (uint256); function mint(uint256 n) external payable; function totalSupply() external view returns (uint256); function transferOwnership(address newOwner) external; function transferFrom( address from, address to, uint256 tokenId ) external; } pragma solidity ^0.8.0; contract MBMinter is PaymentSplitter, Ownable { uint256 public PRICE = 0.05 ether; bool public isAllowListActive = false; bool public isPublicSaleActive = false; address payable public multisig; mapping(address => bool) private _allowList; mapping(address => uint256) private _allowListAmount; mapping(address => uint256) private _allowListClaimed; IMonstersBash nftContract; constructor(address _nftContract, address payable _multisig, address[] memory payees, uint256[] memory shares_) PaymentSplitter(payees, shares_) { nftContract = IMonstersBash(_nftContract); multisig = _multisig; } function addToAllowList(address[] calldata addresses, uint256[] calldata amounts) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); _allowList[addresses[i]] = true; _allowListAmount[addresses[i]] = amounts[i]; /** * @dev We don't want to reset _allowListClaimed count * if we try to add someone more than once. */ _allowListClaimed[addresses[i]] = _allowListClaimed[addresses[i]] > 0 ? _allowListClaimed[addresses[i]] : 0; } } function onAllowList(address addr) external view returns (bool) { return _allowList[addr]; } function removeFromAllowList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); /// @dev We don't want to reset possible _allowListClaimed numbers. _allowList[addresses[i]] = false; _allowListAmount[addresses[i]] = 0; } } /** * @dev We want to be able to distinguish tokens bought during isAllowListActive * and tokens bought outside of isAllowListActive */ function allowListClaimedBy(address owner) external view returns (uint256){ require(owner != address(0), 'Zero address not on Allow List'); return _allowListClaimed[owner]; } /** * @dev How many are left for this address */ function allowListClaimLeft(address owner) external view returns (uint256){ require(owner != address(0), 'Zero address not on Allow List'); return _allowListAmount[owner] - _allowListClaimed[owner]; } function purchaseAllowList(uint256 n) external payable { require(isAllowListActive, 'Allow List is not active'); require(!nftContract.saleIsActive(), 'Sale is already active'); require(_allowList[msg.sender], 'You are not on the Allow List'); require(_allowListClaimed[msg.sender] + n <= _allowListAmount[msg.sender], 'Purchase exceeds max allowed'); // turn on sale nftContract.toggleSaleState(); // increase claimed amount _allowListClaimed[msg.sender] += n; // mint uint256 mintIndex = nftContract.totalSupply(); nftContract.mint(n); for (uint256 i = 0; i < n; i++) { nftContract.transferFrom(address(this), msg.sender, mintIndex + i); } // turn off sale nftContract.toggleSaleState(); } function mint(uint256 n) external payable { require(isPublicSaleActive, 'Public sale is not active'); require(!nftContract.saleIsActive(), 'OG Sale is already active'); require(PRICE * n <= msg.value, 'ETH amount is not sufficient'); // turn on sale nftContract.toggleSaleState(); // mint uint256 mintIndex = nftContract.totalSupply(); nftContract.mint(n); for (uint256 i = 0; i < n; i++) { nftContract.transferFrom(address(this), msg.sender, mintIndex + i); } // turn off sale nftContract.toggleSaleState(); } function giveaway(address to, uint256 n) external onlyOwner { require(!nftContract.saleIsActive(), 'OG Sale is already active'); // turn on sale nftContract.toggleSaleState(); // mint uint256 mintIndex = nftContract.totalSupply(); nftContract.mint(n); for (uint256 i = 0; i < n; i++) { nftContract.transferFrom(address(this), to, mintIndex + i); } // turn off sale nftContract.toggleSaleState(); } function setPrice(uint256 _salePrice) external onlyOwner { PRICE = _salePrice; } function setIsAllowListActive(bool _isAllowListActive) external onlyOwner { isAllowListActive = _isAllowListActive; } function setIsPublicActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function transferOwnerShipOfNft(address newOwner) external onlyOwner { nftContract.transferOwnership(newOwner); } function withdrawMultisig() public onlyOwner { uint256 balance = address(this).balance; payable(multisig).transfer(balance); } function onERC721Received( address, address, uint256, bytes calldata ) external returns (bytes4) { return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } }
turn on sale increase claimed amount mint
function purchaseAllowList(uint256 n) external payable { require(isAllowListActive, 'Allow List is not active'); require(!nftContract.saleIsActive(), 'Sale is already active'); require(_allowList[msg.sender], 'You are not on the Allow List'); require(_allowListClaimed[msg.sender] + n <= _allowListAmount[msg.sender], 'Purchase exceeds max allowed'); nftContract.toggleSaleState(); _allowListClaimed[msg.sender] += n; uint256 mintIndex = nftContract.totalSupply(); nftContract.mint(n); for (uint256 i = 0; i < n; i++) { nftContract.transferFrom(address(this), msg.sender, mintIndex + i); } }
6,707,833
[ 1, 20922, 603, 272, 5349, 10929, 7516, 329, 3844, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 7009, 682, 12, 11890, 5034, 290, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 291, 7009, 682, 3896, 16, 296, 7009, 987, 353, 486, 2695, 8284, 203, 3639, 2583, 12, 5, 82, 1222, 8924, 18, 87, 5349, 2520, 3896, 9334, 296, 30746, 353, 1818, 2695, 8284, 203, 3639, 2583, 24899, 5965, 682, 63, 3576, 18, 15330, 6487, 296, 6225, 854, 486, 603, 326, 7852, 987, 8284, 203, 3639, 2583, 24899, 5965, 682, 9762, 329, 63, 3576, 18, 15330, 65, 397, 290, 1648, 389, 5965, 682, 6275, 63, 3576, 18, 15330, 6487, 296, 23164, 14399, 943, 2935, 8284, 203, 203, 3639, 290, 1222, 8924, 18, 14401, 30746, 1119, 5621, 203, 203, 3639, 389, 5965, 682, 9762, 329, 63, 3576, 18, 15330, 65, 1011, 290, 31, 203, 203, 3639, 2254, 5034, 312, 474, 1016, 273, 290, 1222, 8924, 18, 4963, 3088, 1283, 5621, 203, 3639, 290, 1222, 8924, 18, 81, 474, 12, 82, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 290, 31, 277, 27245, 288, 203, 5411, 290, 1222, 8924, 18, 13866, 1265, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 312, 474, 1016, 397, 277, 1769, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.18; pragma experimental ABIEncoderV2; import "contracts/Zipper.sol"; /// @title Dictionary storing allocations /// @author Giovanni Rescinito /// @notice Data structure implemented as an iterable map, produced during the apportionment algorithm to store allocations library Allocations { //Data Structures /// @notice Data structure related to a single allocation struct Allocation { uint240 shares; // winners per cluster uint16 p; // probability of the allocation } /// @notice Dictionary containing allocations struct Map { Allocation[] elements; // list of allocations mapping (bytes32 => uint) idx; // maps key to index in the list } //Setters /// @notice creates a new allocation or updates the probability of an existing one /// @param map dictionary containing allocations /// @param a winners per cluster to insert/modify /// @param p probability of the specific allocation function setAllocation(Map storage map, uint[] calldata a, uint p) external { bytes32 h = keccak256(abi.encodePacked(a)); uint index = map.idx[h]; if (index == 0) { map.elements.push(Allocation(uint240(Zipper.zipArrayWithSize(a,8)), uint16(p))); map.idx[h] = map.elements.length; }else { map.elements[index - 1].p = uint16(p); } } /// @notice updates the winners per cluster of an allocation specified by its index /// @param map dictionary containing allocations /// @param index index of the allocation to modify /// @param shares winners per cluster to update function updateShares(Map storage map, uint index, uint[] calldata shares) external { require(index >= 0 && index < map.elements.length, "Map out of bounds"); map.elements[index].shares = uint240(Zipper.zipArrayWithSize(shares,8)); } //Getters /// @param map dictionary containing allocations /// @return the number of allocations stored function length(Map storage map) view external returns (uint){ return map.elements.length; } /// @param map dictionary containing allocations /// @return the list of allocations and the list of corresponding probabilities function getAllocations(Map storage map) view external returns (uint[][] memory, uint[] memory) { uint n = map.elements.length; uint[][] memory allocations = new uint[][](n); uint[] memory p = new uint[](n); for (uint i=0;i<n;i++){ allocations[i] = getShares(map.elements[i]); p[i] = map.elements[i].p; } return (allocations,p); } /// @param a allocation for which the probability is required /// @return the probability associated to the allocation function getP(Allocation calldata a) pure external returns (uint) { return a.p; } /// @param a allocation for which the winners per cluster are required /// @return the winners per cluster associated to the allocation function getShares(Allocation memory a) pure public returns (uint[] memory) { return Zipper.unzipArrayWithSize(a.shares,8); } /// @param map dictionary containing allocations /// @param index allocation for which the probability is required /// @return the allocation stored at a specified index function getAllocationAt(Map storage map, uint index) view external returns (Allocation memory) { require(index >= 0 && index < map.elements.length, "Map out of bounds"); return map.elements[index]; } }
winners per cluster
uint240 shares;
6,435,229
[ 1, 8082, 9646, 1534, 2855, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 28784, 24123, 31, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-24 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @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); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_, uint256 totalSupply_) { _name = name_; _symbol = symbol_; _mint(msg.sender, totalSupply_ * (10 **decimals())); } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin Contracts guidelines: functions revert instead returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; } constructor(string memory name_, string memory symbol_, uint256 totalSupply_) { _name = name_; _symbol = symbol_; _mint(msg.sender, totalSupply_ * (10 **decimals())); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } ) internal virtual {} ) internal virtual {} }
2,115,721
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 30131, 9875, 14567, 30, 4186, 15226, 3560, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 97, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 16, 2254, 5034, 2078, 3088, 1283, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2078, 3088, 1283, 67, 380, 261, 2163, 2826, 31734, 1435, 10019, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; /// Tenure is not within minimum and maximum authorized /// @param tenure, actual tenure /// @param minTenure, minimum tenure /// @param maxTenure, maximum tenure error InvalidTenure(uint16 tenure, uint16 minTenure, uint16 maxTenure); /// AdvanceFee is higher than the maxAdvancedRatio /// @param advanceFee, actual advanceFee /// @param maxAdvancedRatio, maximum advanced ratio error InvalidAdvanceFee(uint16 advanceFee, uint16 maxAdvancedRatio); /// DiscountFee is lower than the minDiscountFee /// @param discountFee, actual discountFee /// @param minDiscountFee, minimum discount fee error InvalidDiscountFee(uint16 discountFee, uint16 minDiscountFee); /// FactoringFee is lower than the minDiscountFee /// @param factoringFee, actual factoringFee /// @param minFactoringFee, minimum factoring fee error InvalidFactoringFee(uint16 factoringFee, uint16 minFactoringFee); /// InvoiceAmount is not within minimum and maximum authorized /// @param invoiceAmount, actual invoice amount /// @param minAmount, minimum invoice amount /// @param maxAmount, maximum invoice amount error InvalidInvoiceAmount(uint invoiceAmount, uint minAmount, uint maxAmount); /// Available Amount is higher than Invoice Amount /// @param availableAmount, actual available amount /// @param invoiceAmount, actual invoice amount error InvalidAvailableAmount(uint availableAmount, uint invoiceAmount); /// @title IOffer /// @author Polytrade interface IOffer { struct OfferItem { uint advancedAmount; uint reserve; uint64 disbursingAdvanceDate; OfferParams params; OfferRefunded refunded; } struct OfferParams { uint8 gracePeriod; uint16 tenure; uint16 factoringFee; uint16 discountFee; uint16 advanceFee; address stableAddress; uint invoiceAmount; uint availableAmount; } struct OfferRefunded { uint16 lateFee; uint64 dueDate; uint24 numberOfLateDays; uint totalCalculatedFees; uint netAmount; } /** * @dev Emitted when new offer is created */ event OfferCreated(uint indexed offerId, uint16 pricingId); /** * @dev Emitted when Reserve is refunded */ event ReserveRefunded(uint indexed offerId, uint refundedAmount); /** * @dev Emitted when PricingTable Address is updated */ event NewPricingTableContract( address oldPricingTableAddress, address newPricingTableAddress ); /** * @dev Emitted when PriceFeed Address is updated */ event NewPriceFeedContract( address oldPriceFeedAddress, address newPriceFeedAddress ); /** * @dev Emitted when Treasury Address is updated */ event NewTreasuryAddress( address oldTreasuryAddress, address newTreasuryAddress ); /** * @dev Emitted when LenderPool Address is updated */ event NewLenderPoolAddress( address oldLenderPoolAddress, address newLenderPoolAddress ); /** * @dev Emitted when Oracle usage is activated or deactivated */ event OracleUsageUpdated(bool status); }
Available Amount is higher than Invoice Amount @param availableAmount, actual available amount @param invoiceAmount, actual invoice amount
error InvalidAvailableAmount(uint availableAmount, uint invoiceAmount);
5,395,719
[ 1, 5268, 16811, 353, 10478, 2353, 15458, 16811, 225, 2319, 6275, 16, 3214, 2319, 3844, 225, 9179, 6275, 16, 3214, 9179, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1636, 1962, 5268, 6275, 12, 11890, 2319, 6275, 16, 2254, 9179, 6275, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; import './interfaces/IERC20.sol'; /** * @title Token * @dev Contract that implements ERC20 token standard * Is deployed by `Crowdsale.sol`, keeps track of balances, etc. */ mapping (address => uint256) private _balances; mapping (address => mapping (address =>uint256)) private _allowed; contract Token is IERC20 { /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance){ return _balances[_owner]; } /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success){ //check balance of sender if (_balances[msg.sender] >= _value){ _balances[msg.sender]-= _value; _balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } return false; } /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ //check balance of _spender if (balances[_from] >= _value){ balances[_from]-= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); return true; } return false; } /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success){ //check balance of sender if (_balances[msg.sender] >= _value){ //_balances[msg.sender]-= _value; _allowed[msg.sender][_spender] += _value; emit Approval(msg.sender, spender, _value); return true; } return false; } /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return _allowed[owner][spender]; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
@param _owner The address from which the balance will be retrieved @return The balance
function balanceOf(address _owner) constant returns (uint256 balance){ return _balances[_owner]; }
15,865,584
[ 1, 67, 8443, 1021, 1758, 628, 1492, 326, 11013, 903, 506, 10295, 327, 1021, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 445, 11013, 951, 12, 2867, 389, 8443, 13, 5381, 1135, 261, 11890, 5034, 11013, 15329, 203, 3639, 327, 389, 70, 26488, 63, 67, 8443, 15533, 203, 1377, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/EditionIndexerProxiedV1.sol
@author Guillaume Gonnaud 2019 @title Cryptograph Edition Indexer Proxy Smart Contract @notice The proxied Edition Indexer : this is the contract that will be instancied on the blockchain. Cast this as the logic contract to interact with it.
contract EditionIndexerProxiedV1 is VCProxy, EditionIndexerHeaderV1, EditionIndexerStorageInternalV1 { constructor(uint256 _version, address _vc) public pragma solidity 0.6.6; { } }
3,151,892
[ 1, 6099, 10745, 2066, 611, 265, 6582, 1100, 30562, 282, 22752, 8829, 512, 1460, 3340, 264, 7659, 19656, 13456, 225, 1021, 21875, 512, 1460, 3340, 264, 294, 333, 353, 326, 6835, 716, 903, 506, 316, 27866, 2092, 603, 326, 16766, 18, 19782, 333, 487, 326, 4058, 6835, 358, 16592, 598, 518, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 512, 1460, 20877, 16155, 2092, 58, 21, 353, 776, 39, 3886, 16, 512, 1460, 20877, 1864, 58, 21, 16, 512, 1460, 20877, 3245, 3061, 58, 21, 225, 288, 203, 203, 565, 3885, 12, 11890, 5034, 389, 1589, 16, 1758, 389, 4227, 13, 225, 1071, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 26, 31, 203, 565, 288, 203, 565, 289, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x9038f97B030B5F5c63e8eEc4a81A65E0d7808A4D/sources/McBaseAutoStrategyCake.sol
* @dev Tokens Used: {wbnb} - Required for liquidity routing when doing swaps. {Auto} - Token generated by staking our funds. In this case it's the AUTO token. {want} - Token that the strategy maximizes. {bifi} - BeefyFinance token, used to send funds to the treasury./* @dev Third Party Contracts: {unirouter} - PancakeSwap unirouter {autofarm} - AutoFarm contract {masterchef} - PancakeSwap MasterChef contract {autostrat} - AutoFarm underlying strategy contract {poolId} - AutoFarm pool id/* @dev Beefy Contracts: {rewards} - Reward pool where the strategy fee earnings will go. {treasury} - Address of the BeefyFinance treasury {vault} - Address of the vault that controls the strategy's funds. {strategist} - Address of the strategy author/deployer where strategist fee will go./* @dev Distribution of fees earned. This allocations relative to the % implemented on doSplit(). Current implementation separates 5% for fees. {REWARDS_FEE} - 4% goes to mcbase-bnb vault. {TREASURY_FEE} - 1% goes to the treasury. {MAX_FEE} - Aux const used to safely calc the correct amounts. {WITHDRAWAL_FEE} - Fee taxed when a user withdraws funds. 10 === 0.1% fee. {WITHDRAWAL_MAX} - Aux const used to safely calc the correct amounts./* @dev Routes we take to swap tokens using PancakeSwap. {autoToWbnbRoute} - Route we take to go from {auto} into {wbnb}. {autoToWantRoute} - Route we take to go from {auto} into {want}./* @dev Event that is fired each time someone harvests the strat./* @dev Initializes the strategy with the token to maximize./
constructor(address _want, uint8 _poolId, address _vault) public { want = _want; poolId = _poolId; vault = _vault; (, , , , address _autostrat) = IAutoFarmV2(autofarm).poolInfo(poolId); autostrat = _autostrat; if (want == wbnb) { autoToWantRoute = [Auto, wbnb]; autoToWantRoute = [Auto, wbnb, want]; } IERC20(want).safeApprove(autofarm, uint(-1)); IERC20(Auto).safeApprove(unirouter, uint(-1)); IERC20(wbnb).safeApprove(unirouter, uint(-1)); }
11,249,997
[ 1, 5157, 10286, 30, 288, 9464, 6423, 97, 300, 10647, 364, 4501, 372, 24237, 7502, 1347, 9957, 1352, 6679, 18, 288, 4965, 97, 300, 3155, 4374, 635, 384, 6159, 3134, 284, 19156, 18, 657, 333, 648, 518, 1807, 326, 17191, 1147, 18, 288, 17369, 97, 300, 3155, 716, 326, 6252, 30547, 3128, 18, 288, 70, 704, 97, 300, 30830, 74, 93, 6187, 1359, 1147, 16, 1399, 358, 1366, 284, 19156, 358, 326, 9787, 345, 22498, 18, 19, 225, 935, 6909, 6393, 93, 30131, 30, 288, 318, 77, 10717, 97, 300, 12913, 23780, 12521, 7738, 10717, 288, 5854, 792, 4610, 97, 300, 8064, 42, 4610, 6835, 288, 7525, 343, 10241, 97, 300, 12913, 23780, 12521, 13453, 39, 580, 74, 6835, 288, 21996, 313, 270, 97, 300, 8064, 42, 4610, 6808, 6252, 6835, 288, 6011, 548, 97, 300, 8064, 42, 4610, 2845, 612, 19, 225, 30830, 74, 93, 30131, 30, 288, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 3885, 12, 2867, 389, 17369, 16, 2254, 28, 389, 6011, 548, 16, 1758, 389, 26983, 13, 1071, 288, 203, 3639, 2545, 273, 389, 17369, 31, 203, 3639, 2845, 548, 273, 389, 6011, 548, 31, 203, 3639, 9229, 273, 389, 26983, 31, 203, 203, 3639, 261, 16, 269, 269, 269, 1758, 389, 21996, 313, 270, 13, 273, 467, 4965, 42, 4610, 58, 22, 12, 5854, 792, 4610, 2934, 6011, 966, 12, 6011, 548, 1769, 203, 3639, 13133, 313, 270, 273, 389, 21996, 313, 270, 31, 203, 203, 3639, 309, 261, 17369, 422, 17298, 6423, 13, 288, 203, 5411, 3656, 774, 59, 970, 3255, 273, 306, 4965, 16, 17298, 6423, 15533, 203, 5411, 3656, 774, 59, 970, 3255, 273, 306, 4965, 16, 17298, 6423, 16, 2545, 15533, 203, 3639, 289, 203, 203, 3639, 467, 654, 39, 3462, 12, 17369, 2934, 4626, 12053, 537, 12, 5854, 792, 4610, 16, 2254, 19236, 21, 10019, 203, 3639, 467, 654, 39, 3462, 12, 4965, 2934, 4626, 12053, 537, 12, 318, 77, 10717, 16, 2254, 19236, 21, 10019, 203, 3639, 467, 654, 39, 3462, 12, 9464, 6423, 2934, 4626, 12053, 537, 12, 318, 77, 10717, 16, 2254, 19236, 21, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xA4c8A48414d80B22c50BE7b6f3CfAE3EfA6a8716 //Contract name: PPNAirdrop //Balance: 0 Ether //Verification Date: 6/12/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.18; contract PPNAirdrop { /** * @dev Air drop Public Variables */ address public admin; PolicyPalNetworkToken public token; using SafeMath for uint256; /** * @dev Token Contract Modifier * Check if only admin * */ modifier onlyAdmin() { require(msg.sender == admin); _; } /** * @dev Token Contract Modifier * Check if valid address * * @param _addr - The address to check * */ modifier validAddress(address _addr) { require(_addr != address(0x0)); require(_addr != address(this)); _; } /** * @dev Token Contract Modifier * Check if the batch transfer amount is * equal or more than balance * (For single batch amount) * * @param _recipients - The recipients to send * @param _amount - The amount to send * */ modifier validBalance(address[] _recipients, uint256 _amount) { // Assert balance uint256 balance = token.balanceOf(this); require(balance > 0); require(balance >= _recipients.length.mul(_amount)); _; } /** * @dev Token Contract Modifier * Check if the batch transfer amount is * equal or more than balance * (For multiple batch amounts) * * @param _recipients - The recipients to send * @param _amounts - The amounts to send * */ modifier validBalanceMultiple(address[] _recipients, uint256[] _amounts) { // Assert balance uint256 balance = token.balanceOf(this); require(balance > 0); uint256 totalAmount; for (uint256 i = 0 ; i < _recipients.length ; i++) { totalAmount = totalAmount.add(_amounts[i]); } require(balance >= totalAmount); _; } /** * @dev Airdrop Contract Constructor * @param _token - PPN Token address * @param _adminAddr - Address of the Admin */ function PPNAirdrop( PolicyPalNetworkToken _token, address _adminAddr ) public validAddress(_adminAddr) validAddress(_token) { // Assign addresses admin = _adminAddr; token = _token; } /** * @dev TokenDrop Event */ event TokenDrop(address _receiver, uint _amount); /** * @dev batch Air Drop by single amount * @param _recipients - Address of the recipient * @param _amount - Amount to transfer used in this batch */ function batchSingleAmount(address[] _recipients, uint256 _amount) external onlyAdmin validBalance(_recipients, _amount) { // Loop through all recipients for (uint256 i = 0 ; i < _recipients.length ; i++) { address recipient = _recipients[i]; // Transfer amount assert(token.transfer(recipient, _amount)); // TokenDrop event TokenDrop(recipient, _amount); } } /** * @dev batch Air Drop by multiple amount * @param _recipients - Address of the recipient * @param _amounts - Amount to transfer used in this batch */ function batchMultipleAmount(address[] _recipients, uint256[] _amounts) external onlyAdmin validBalanceMultiple(_recipients, _amounts) { // Loop through all recipients for (uint256 i = 0 ; i < _recipients.length ; i++) { address recipient = _recipients[i]; uint256 amount = _amounts[i]; // Transfer amount assert(token.transfer(recipient, amount)); // TokenDrop event TokenDrop(recipient, amount); } } /** * @dev Air drop single amount * @param _recipient - Address of the recipient * @param _amount - Amount to drain */ function airdropSingleAmount(address _recipient, uint256 _amount) external onlyAdmin { assert(_amount <= token.balanceOf(this)); assert(token.transfer(_recipient, _amount)); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract PolicyPalNetworkToken is StandardToken, BurnableToken, Ownable { /** * @dev Token Contract Constants */ string public constant name = "PolicyPal Network Token"; string public constant symbol = "PAL"; uint8 public constant decimals = 18; /** * @dev Token Contract Public Variables */ address public tokenSaleContract; bool public isTokenTransferable = false; /** * @dev Token Contract Modifier * * Check if a transfer is allowed * Transfers are restricted to token creator & owner(admin) during token sale duration * Transfers after token sale is limited by `isTokenTransferable` toggle * */ modifier onlyWhenTransferAllowed() { require(isTokenTransferable || msg.sender == owner || msg.sender == tokenSaleContract); _; } /** * @dev Token Contract Modifier * @param _to - Address to check if valid * * Check if an address is valid * A valid address is as follows, * 1. Not zero address * 2. Not token address * */ modifier isValidDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); _; } /** * @dev Enable Transfers (Only Owner) */ function toggleTransferable(bool _toggle) external onlyOwner { isTokenTransferable = _toggle; } /** * @dev Token Contract Constructor * @param _adminAddr - Address of the Admin */ function PolicyPalNetworkToken( uint _tokenTotalAmount, address _adminAddr ) public isValidDestination(_adminAddr) { require(_tokenTotalAmount > 0); totalSupply_ = _tokenTotalAmount; // Mint all token balances[msg.sender] = _tokenTotalAmount; Transfer(address(0x0), msg.sender, _tokenTotalAmount); // Assign token sale contract to creator tokenSaleContract = msg.sender; // Transfer contract ownership to admin transferOwnership(_adminAddr); } /** * @dev Token Contract transfer * @param _to - Address to transfer to * @param _value - Value to transfer * @return bool - Result of transfer * "Overloaded" Function of ERC20Basic's transfer * */ function transfer(address _to, uint256 _value) public onlyWhenTransferAllowed isValidDestination(_to) returns (bool) { return super.transfer(_to, _value); } /** * @dev Token Contract transferFrom * @param _from - Address to transfer from * @param _to - Address to transfer to * @param _value - Value to transfer * @return bool - Result of transferFrom * * "Overloaded" Function of ERC20's transferFrom * Added with modifiers, * 1. onlyWhenTransferAllowed * 2. isValidDestination * */ function transferFrom(address _from, address _to, uint256 _value) public onlyWhenTransferAllowed isValidDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Token Contract burn * @param _value - Value to burn * "Overloaded" Function of BurnableToken's burn */ function burn(uint256 _value) public { super.burn(_value); Transfer(msg.sender, address(0x0), _value); } /** * @dev Token Contract Emergency Drain * @param _token - Token to drain * @param _amount - Amount to drain */ function emergencyERC20Drain(ERC20 _token, uint256 _amount) public onlyOwner { _token.transfer(owner, _amount); } }
* @dev Token Contract Modifier @param _to - Address to check if valid Check if an address is valid A valid address is as follows, 1. Not zero address 2. Not token address/
modifier isValidDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); _; }
6,440,662
[ 1, 1345, 13456, 12832, 225, 389, 869, 300, 5267, 358, 866, 309, 923, 225, 2073, 309, 392, 1758, 353, 923, 225, 432, 923, 1758, 353, 487, 13040, 16, 565, 404, 18, 2288, 3634, 1758, 565, 576, 18, 2288, 1147, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 4908, 5683, 12, 2867, 389, 869, 13, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 2211, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xFC27e230EF6737F0178eF4E7B8Ea11A4f4955977/sources/_beandao/contracts/library/ERC2612.sol
* @notice Verify a signed approval permit and execute if valid @param owner Token owner's address (Authorizer) @param spender Spender's address @param value Amount of allowance @param deadline The time at which this expires (unix time) @param v v of the signature @param r r of the signature @param s s of the signature/
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual { require(owner != address(0), "ERC2612/Invalid-address-0"); require(deadline >= block.timestamp, "ERC2612/Expired-time"); bytes32 digest = EIP712.hashMessage( DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ); address recovered = ecrecover(digest, v, r, s); require(recovered != address(0) && recovered == owner, "ERC2612/Invalid-Signature"); _approve(owner, spender, value); }
11,585,980
[ 1, 8097, 279, 6726, 23556, 21447, 471, 1836, 309, 923, 225, 3410, 377, 3155, 3410, 1807, 1758, 261, 17170, 13, 225, 17571, 264, 282, 348, 1302, 264, 1807, 1758, 225, 460, 377, 16811, 434, 1699, 1359, 225, 14096, 225, 1021, 813, 622, 1492, 333, 7368, 261, 21136, 813, 13, 225, 331, 540, 331, 434, 326, 3372, 225, 436, 540, 436, 434, 326, 3372, 225, 272, 540, 272, 434, 326, 3372, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 21447, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 5024, 288, 203, 3639, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 654, 39, 5558, 2138, 19, 1941, 17, 2867, 17, 20, 8863, 203, 3639, 2583, 12, 22097, 1369, 1545, 1203, 18, 5508, 16, 315, 654, 39, 5558, 2138, 19, 10556, 17, 957, 8863, 203, 203, 3639, 1731, 1578, 5403, 273, 512, 2579, 27, 2138, 18, 2816, 1079, 12, 203, 5411, 27025, 67, 4550, 16, 203, 5411, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 3194, 6068, 67, 2399, 15920, 16, 3410, 16, 17571, 264, 16, 460, 16, 1661, 764, 63, 8443, 3737, 15, 16, 14096, 3719, 203, 3639, 11272, 203, 203, 3639, 1758, 24616, 273, 425, 1793, 3165, 12, 10171, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 2583, 12, 266, 16810, 480, 1758, 12, 20, 13, 597, 24616, 422, 3410, 16, 315, 654, 39, 5558, 2138, 19, 1941, 17, 5374, 8863, 203, 203, 3639, 389, 12908, 537, 12, 8443, 16, 17571, 264, 16, 460, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20 { function totalSupply() public view returns (uint256); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract SafeMath { function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } function safeDiv(uint256 x, uint256 y) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 z = x / y; return z; } } contract StandardToken is ERC20, SafeMath { /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4) ; _; } mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public returns (bool){ require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = safeSubtract(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); uint _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSubtract(balances[_from], _value); allowed[_from][msg.sender] = safeSubtract(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint) { return balances[_owner]; } function approve(address _spender, uint _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint) { return allowed[_owner][_spender]; } } contract EPay is StandardToken { string public constant name = "EPay"; string public constant symbol = "EPAY"; uint256 public constant decimals = 18; string public version = "1.0"; uint256 public constant total = 98 * (10**6) * 10**decimals; // 98 *10^6 EPay total function EPay() public { balances[msg.sender] = total; Transfer(0x0, msg.sender, total); } function totalSupply() public view returns (uint256) { return total; } function transfer(address _to, uint _value) public returns (bool) { return super.transfer(_to,_value); } function approve(address _spender, uint _value) public returns (bool) { return super.approve(_spender,_value); } function airdropToAddresses(address[] addrs, uint256 amount) public { for (uint256 i = 0; i < addrs.length; i++) { transfer(addrs[i], amount); } } }
98 *10^6 EPay total
uint256 public constant total = 98 * (10**6) * 10**decimals;
2,240,758
[ 1, 10689, 1728, 66, 26, 512, 9148, 2078, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 5381, 2078, 273, 24645, 380, 261, 2163, 636, 26, 13, 380, 1728, 636, 31734, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xA4F902f57Fd9FFcedF4dE6cF7EbC86ea9F76B5d1 //Contract name: EtheraffleICO //Balance: 7.348300000000000094 Ether //Verification Date: 3/7/2018 //Transacion Count: 28 // CODE STARTS HERE pragma solidity^0.4.15; contract EtheraffleLOT { function mint(address _to, uint _amt) external {} function transfer(address to, uint value) public {} function balanceOf(address who) constant public returns (uint) {} } contract EtheraffleICO is EtheraffleLOT { /* Lot reward per ether in each tier */ uint public constant tier0LOT = 110000 * 10 ** 6; uint public constant tier1LOT = 100000 * 10 ** 6; uint public constant tier2LOT = 90000 * 10 ** 6; uint public constant tier3LOT = 80000 * 10 ** 6; /* Bonus tickets multiplier */ uint public constant bonusLOT = 1500 * 10 ** 6; uint public constant bonusFreeLOT = 10; /* Maximum amount of ether investable per tier */ uint public constant maxWeiTier0 = 700 * 10 ** 18; uint public constant maxWeiTier1 = 2500 * 10 ** 18; uint public constant maxWeiTier2 = 7000 * 10 ** 18; uint public constant maxWeiTier3 = 20000 * 10 ** 18; /* Minimum investment (0.025 Ether) */ uint public constant minWei = 25 * 10 ** 15; /* Crowdsale open, close, withdraw & tier times (UTC Format)*/ uint public ICOStart = 1522281600;//Thur 29th March 2018 uint public tier1End = 1523491200;//Thur 12th April 2018 uint public tier2End = 1525305600;//Thur 3rd May 2018 uint public tier3End = 1527724800;//Thur 31st May 2018 uint public wdBefore = 1528934400;//Thur 14th June 2018 /* Variables to track amount of purchases in tier */ uint public tier0Total; uint public tier1Total; uint public tier2Total; uint public tier3Total; /* Etheraffle's multisig wallet & LOT token addresses */ address public etheraffle; /* ICO status toggle */ bool public ICORunning = true; /* Map of purchaser's ethereum addresses to their purchase amounts for calculating bonuses*/ mapping (address => uint) public tier0; mapping (address => uint) public tier1; mapping (address => uint) public tier2; mapping (address => uint) public tier3; /* Instantiate the variables to hold Etheraffle's LOT & freeLOT token contract instances */ EtheraffleLOT LOT; EtheraffleLOT FreeLOT; /* Event loggers */ event LogTokenDeposit(address indexed from, uint value, bytes data); event LogRefund(address indexed toWhom, uint amountOfEther, uint atTime); event LogEtherTransfer(address indexed toWhom, uint amount, uint atTime); event LogBonusLOTRedemption(address indexed toWhom, uint lotAmount, uint atTime); event LogLOTTransfer(address indexed toWhom, uint indexed inTier, uint ethAmt, uint LOTAmt, uint atTime); /** * @dev Modifier function to prepend to later functions in this contract in * order to redner them only useable by the Etheraffle address. */ modifier onlyEtheraffle() { require(msg.sender == etheraffle); _; } /** * @dev Modifier function to prepend to later functions rendering the method * only callable if the crowdsale is running. */ modifier onlyIfRunning() { require(ICORunning); _; } /** * @dev Modifier function to prepend to later functions rendering the method * only callable if the crowdsale is NOT running. */ modifier onlyIfNotRunning() { require(!ICORunning); _; } /** * @dev Constructor. Sets up the variables pertaining to the ICO start & * end times, the tier start & end times, the Etheraffle MultiSig Wallet * address & the Etheraffle LOT & FreeLOT token contracts. */ function EtheraffleICO() public {//address _LOT, address _freeLOT, address _msig) public { etheraffle = 0x97f535e98cf250cdd7ff0cb9b29e4548b609a0bd; LOT = EtheraffleLOT(0xAfD9473dfe8a49567872f93c1790b74Ee7D92A9F); FreeLOT = EtheraffleLOT(0xc39f7bB97B31102C923DaF02bA3d1bD16424F4bb); } /** * @dev Purchase LOT tokens. * LOT are sent in accordance with how much ether is invested, and in what * tier the investment was made. The function also stores the amount of ether * invested for later conversion to the amount of bonus LOT owed. Once the * crowdsale is over and the final number of tokens sold is known, the purchaser's * bonuses can be calculated. Using the fallback function allows LOT purchasers to * simply send ether to this address in order to purchase LOT, without having * to call a function. The requirements also also mean that once the crowdsale is * over, any ether sent to this address by accident will be returned to the sender * and not lost. */ function () public payable onlyIfRunning { /* Requires the crowdsale time window to be open and the function caller to send ether */ require ( now <= tier3End && msg.value >= minWei ); uint numLOT = 0; if (now <= ICOStart) {// ∴ tier zero... /* Eth investable in each tier is capped via this requirement */ require(tier0Total + msg.value <= maxWeiTier0); /* Store purchasers purchased amount for later bonus redemption */ tier0[msg.sender] += msg.value; /* Track total investment in tier one for later bonus calculation */ tier0Total += msg.value; /* Number of LOT this tier's purchase results in */ numLOT = (msg.value * tier0LOT) / (1 * 10 ** 18); /* Transfer the number of LOT bought to the purchaser */ LOT.transfer(msg.sender, numLOT); /* Log the transfer */ LogLOTTransfer(msg.sender, 0, msg.value, numLOT, now); return; } else if (now <= tier1End) {// ∴ tier one... require(tier1Total + msg.value <= maxWeiTier1); tier1[msg.sender] += msg.value; tier1Total += msg.value; numLOT = (msg.value * tier1LOT) / (1 * 10 ** 18); LOT.transfer(msg.sender, numLOT); LogLOTTransfer(msg.sender, 1, msg.value, numLOT, now); return; } else if (now <= tier2End) {// ∴ tier two... require(tier2Total + msg.value <= maxWeiTier2); tier2[msg.sender] += msg.value; tier2Total += msg.value; numLOT = (msg.value * tier2LOT) / (1 * 10 ** 18); LOT.transfer(msg.sender, numLOT); LogLOTTransfer(msg.sender, 2, msg.value, numLOT, now); return; } else {// ∴ tier three... require(tier3Total + msg.value <= maxWeiTier3); tier3[msg.sender] += msg.value; tier3Total += msg.value; numLOT = (msg.value * tier3LOT) / (1 * 10 ** 18); LOT.transfer(msg.sender, numLOT); LogLOTTransfer(msg.sender, 3, msg.value, numLOT, now); return; } } /** * @dev Redeem bonus LOT: This function cannot be called until * the crowdsale is over, nor after the withdraw period. * During this window, a LOT purchaser calls this function * in order to receive their bonus LOT owed to them, as * calculated by their share of the total amount of LOT * sales in the tier(s) following their purchase. Once * claimed, user's purchased amounts are set to 1 wei rather * than zero, to allow the contract to maintain a list of * purchasers in each. All investors, regardless of tier/amount, * receive ten free entries into the flagship Saturday * Etheraffle via the FreeLOT coupon. */ function redeemBonusLot() external onlyIfRunning { //81k gas /* Requires crowdsale to be over and the wdBefore time to not have passed yet */ require ( now > tier3End && now < wdBefore ); /* Requires user to have a LOT purchase in at least one of the tiers. */ require ( tier0[msg.sender] > 1 || tier1[msg.sender] > 1 || tier2[msg.sender] > 1 || tier3[msg.sender] > 1 ); uint bonusNumLOT; /* If purchaser has ether in this tier, LOT tokens owed is calculated and added to LOT amount */ if(tier0[msg.sender] > 1) { bonusNumLOT += /* Calculate share of bonus LOT user is entitled to, based on tier one sales */ ((tier1Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18))) + /* Calculate share of bonus LOT user is entitled to, based on tier two sales */ ((tier2Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18))) + /* Calculate share of bonus LOT user is entitled to, based on tier three sales */ ((tier3Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18))); /* Set amount of ether in this tier to 1 to make further bonus redemptions impossible */ tier0[msg.sender] = 1; } if(tier1[msg.sender] > 1) { bonusNumLOT += ((tier2Total * bonusLOT * tier1[msg.sender]) / (tier1Total * (1 * 10 ** 18))) + ((tier3Total * bonusLOT * tier1[msg.sender]) / (tier1Total * (1 * 10 ** 18))); tier1[msg.sender] = 1; } if(tier2[msg.sender] > 1) { bonusNumLOT += ((tier3Total * bonusLOT * tier2[msg.sender]) / (tier2Total * (1 * 10 ** 18))); tier2[msg.sender] = 1; } if(tier3[msg.sender] > 1) { tier3[msg.sender] = 1; } /* Final check that user cannot withdraw twice */ require ( tier0[msg.sender] <= 1 && tier1[msg.sender] <= 1 && tier2[msg.sender] <= 1 && tier3[msg.sender] <= 1 ); /* Transfer bonus LOT to bonus redeemer */ if(bonusNumLOT > 0) { LOT.transfer(msg.sender, bonusNumLOT); } /* Mint FreeLOT and give to bonus redeemer */ FreeLOT.mint(msg.sender, bonusFreeLOT); /* Log the bonus LOT redemption */ LogBonusLOTRedemption(msg.sender, bonusNumLOT, now); } /** * @dev Should crowdsale be cancelled for any reason once it has * begun, any ether is refunded to the purchaser by calling * this funcion. Function checks each tier in turn, totalling * the amount whilst zeroing the balance, and finally makes * the transfer. */ function refundEther() external onlyIfNotRunning { uint amount; if(tier0[msg.sender] > 1) { /* Add balance of caller's address in this tier to the amount */ amount += tier0[msg.sender]; /* Zero callers balance in this tier */ tier0[msg.sender] = 0; } if(tier1[msg.sender] > 1) { amount += tier1[msg.sender]; tier1[msg.sender] = 0; } if(tier2[msg.sender] > 1) { amount += tier2[msg.sender]; tier2[msg.sender] = 0; } if(tier3[msg.sender] > 1) { amount += tier3[msg.sender]; tier3[msg.sender] = 0; } /* Final check that user cannot be refunded twice */ require ( tier0[msg.sender] == 0 && tier1[msg.sender] == 0 && tier2[msg.sender] == 0 && tier3[msg.sender] == 0 ); /* Transfer the ether to the caller */ msg.sender.transfer(amount); /* Log the refund */ LogRefund(msg.sender, amount, now); return; } /** * @dev Function callable only by Etheraffle's multi-sig wallet. It * transfers the tier's raised ether to the etheraffle multisig wallet * once the tier is over. * * @param _tier The tier from which the withdrawal is being made. */ function transferEther(uint _tier) external onlyIfRunning onlyEtheraffle { if(_tier == 0) { /* Require tier zero to be over and a tier zero ether be greater than 0 */ require(now > ICOStart && tier0Total > 0); /* Transfer the tier zero total to the etheraffle multisig */ etheraffle.transfer(tier0Total); /* Log the transfer event */ LogEtherTransfer(msg.sender, tier0Total, now); return; } else if(_tier == 1) { require(now > tier1End && tier1Total > 0); etheraffle.transfer(tier1Total); LogEtherTransfer(msg.sender, tier1Total, now); return; } else if(_tier == 2) { require(now > tier2End && tier2Total > 0); etheraffle.transfer(tier2Total); LogEtherTransfer(msg.sender, tier2Total, now); return; } else if(_tier == 3) { require(now > tier3End && tier3Total > 0); etheraffle.transfer(tier3Total); LogEtherTransfer(msg.sender, tier3Total, now); return; } else if(_tier == 4) { require(now > tier3End && this.balance > 0); etheraffle.transfer(this.balance); LogEtherTransfer(msg.sender, this.balance, now); return; } } /** * @dev Function callable only by Etheraffle's multi-sig wallet. * It transfers any remaining unsold LOT tokens to the * Etheraffle multisig wallet. Function only callable once * the withdraw period and ∴ the ICO ends. */ function transferLOT() onlyEtheraffle onlyIfRunning external { require(now > wdBefore); uint amt = LOT.balanceOf(this); LOT.transfer(etheraffle, amt); LogLOTTransfer(msg.sender, 5, 0, amt, now); } /** * @dev Toggle crowdsale status. Only callable by the Etheraffle * mutlisig account. If set to false, the refund function * becomes live allow purchasers to withdraw their ether * */ function setCrowdSaleStatus(bool _status) external onlyEtheraffle { ICORunning = _status; } /** * @dev This function is what allows this contract to receive ERC223 * compliant tokens. Any tokens sent to this address will fire off * an event announcing their arrival. Unlike ERC20 tokens, ERC223 * tokens cannot be sent to contracts absent this function, * thereby preventing loss of tokens by mistakenly sending them to * contracts not designed to accept them. * * @param _from From whom the transfer originated * @param _value How many tokens were sent * @param _data Transaction metadata */ function tokenFallback(address _from, uint _value, bytes _data) public { if (_value > 0) { LogTokenDeposit(_from, _value, _data); } } /** * @dev Housekeeping function in the event this contract is no * longer needed. Will delete the code from the blockchain. */ function selfDestruct() external onlyIfNotRunning onlyEtheraffle { selfdestruct(etheraffle); } }
* @dev Housekeeping function in the event this contract is no longer needed. Will delete the code from the blockchain./
function selfDestruct() external onlyIfNotRunning onlyEtheraffle { selfdestruct(etheraffle); }
13,066,157
[ 1, 44, 3793, 10102, 310, 445, 316, 326, 871, 333, 6835, 353, 1158, 3639, 7144, 3577, 18, 9980, 1430, 326, 981, 628, 326, 16766, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 365, 6305, 8813, 1435, 3903, 1338, 10288, 7051, 1338, 41, 1136, 7329, 298, 288, 203, 3639, 365, 5489, 8813, 12, 2437, 7329, 298, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract DelegateERC20 { function delegateTotalSupply() public view returns (uint256); function delegateBalanceOf(address who) public view returns (uint256); function delegateTransfer(address to, uint256 value, address origSender) public returns (bool); function delegateAllowance(address owner, address spender) public view returns (uint256); function delegateTransferFrom(address from, address to, uint256 value, address origSender) public returns (bool); function delegateApprove(address spender, uint256 value, address origSender) public returns (bool); function delegateIncreaseApproval(address spender, uint addedValue, address origSender) public returns (bool); function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) public returns (bool); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract AddressList is Claimable { string public name; mapping (address => bool) public onList; function AddressList(string _name, bool nullValue) public { name = _name; onList[0x0] = nullValue; } event ChangeWhiteList(address indexed to, bool onList); // Set whether _to is on the list or not. Whether 0x0 is on the list // or not cannot be set here - it is set once and for all by the constructor. function changeList(address _to, bool _onList) onlyOwner public { require(_to != 0x0); if (onList[_to] != _onList) { onList[_to] = _onList; ChangeWhiteList(_to, _onList); } } } contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } contract TimeLockedController is HasNoEther, HasNoTokens, Claimable { using SafeMath for uint256; // 24 hours, assuming a 15 second blocktime. // As long as this isn't too far off from reality it doesn't really matter. uint public constant blocksDelay = 24*60*60/15; struct MintOperation { address to; uint256 amount; address admin; uint deferBlock; } struct TransferChildOperation { Ownable child; address newOwner; address admin; uint deferBlock; } struct ReclaimOperation { Ownable other; address admin; uint deferBlock; } struct ChangeBurnBoundsOperation { uint newMin; uint newMax; address admin; uint deferBlock; } struct ChangeStakingFeesOperation { uint80 _transferFeeNumerator; uint80 _transferFeeDenominator; uint80 _mintFeeNumerator; uint80 _mintFeeDenominator; uint256 _mintFeeFlat; uint80 _burnFeeNumerator; uint80 _burnFeeDenominator; uint256 _burnFeeFlat; address admin; uint deferBlock; } struct ChangeStakerOperation { address newStaker; address admin; uint deferBlock; } struct DelegateOperation { DelegateERC20 delegate; address admin; uint deferBlock; } struct SetDelegatedFromOperation { address source; address admin; uint deferBlock; } struct ChangeTrueUSDOperation { TrueUSD newContract; address admin; uint deferBlock; } struct ChangeNameOperation { string name; string symbol; address admin; uint deferBlock; } address public admin; TrueUSD public trueUSD; MintOperation[] public mintOperations; TransferChildOperation[] public transferChildOperations; ReclaimOperation[] public reclaimOperations; ChangeBurnBoundsOperation public changeBurnBoundsOperation; ChangeStakingFeesOperation public changeStakingFeesOperation; ChangeStakerOperation public changeStakerOperation; DelegateOperation public delegateOperation; SetDelegatedFromOperation public setDelegatedFromOperation; ChangeTrueUSDOperation public changeTrueUSDOperation; ChangeNameOperation public changeNameOperation; modifier onlyAdminOrOwner() { require(msg.sender == admin || msg.sender == owner); _; } function computeDeferBlock() private view returns (uint) { if (msg.sender == owner) { return block.number; } else { return block.number.add(blocksDelay); } } // starts with no admin function TimeLockedController(address _trueUSD) public { trueUSD = TrueUSD(_trueUSD); } event MintOperationEvent(address indexed _to, uint256 amount, uint deferBlock, uint opIndex); event TransferChildOperationEvent(address indexed _child, address indexed _newOwner, uint deferBlock, uint opIndex); event ReclaimOperationEvent(address indexed other, uint deferBlock, uint opIndex); event ChangeBurnBoundsOperationEvent(uint newMin, uint newMax, uint deferBlock); event ChangeStakingFeesOperationEvent(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat, uint deferBlock); event ChangeStakerOperationEvent(address newStaker, uint deferBlock); event DelegateOperationEvent(DelegateERC20 delegate, uint deferBlock); event SetDelegatedFromOperationEvent(address source, uint deferBlock); event ChangeTrueUSDOperationEvent(TrueUSD newContract, uint deferBlock); event ChangeNameOperationEvent(string name, string symbol, uint deferBlock); event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin); // admin initiates a request to mint _amount TrueUSD for account _to function requestMint(address _to, uint256 _amount) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); MintOperation memory op = MintOperation(_to, _amount, admin, deferBlock); MintOperationEvent(_to, _amount, deferBlock, mintOperations.length); mintOperations.push(op); } // admin initiates a request to transfer _child to _newOwner // Can be used e.g. to upgrade this TimeLockedController contract. function requestTransferChild(Ownable _child, address _newOwner) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); TransferChildOperation memory op = TransferChildOperation(_child, _newOwner, admin, deferBlock); TransferChildOperationEvent(_child, _newOwner, deferBlock, transferChildOperations.length); transferChildOperations.push(op); } // admin initiates a request to transfer ownership of a contract from trueUSD // to this TimeLockedController. Can be used e.g. to reclaim balance sheet // in order to transfer it to an upgraded TrueUSD contract. function requestReclaim(Ownable other) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); ReclaimOperation memory op = ReclaimOperation(other, admin, deferBlock); ReclaimOperationEvent(other, deferBlock, reclaimOperations.length); reclaimOperations.push(op); } // admin initiates a request that the minimum and maximum amounts that any TrueUSD user can // burn become newMin and newMax function requestChangeBurnBounds(uint newMin, uint newMax) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeBurnBoundsOperation = ChangeBurnBoundsOperation(newMin, newMax, admin, deferBlock); ChangeBurnBoundsOperationEvent(newMin, newMax, deferBlock); } // admin initiates a request that the staking fee be changed function requestChangeStakingFees(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeStakingFeesOperation = ChangeStakingFeesOperation(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat, admin, deferBlock); ChangeStakingFeesOperationEvent(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat, deferBlock); } // admin initiates a request that the recipient of the staking fee be changed to newStaker function requestChangeStaker(address newStaker) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeStakerOperation = ChangeStakerOperation(newStaker, admin, deferBlock); ChangeStakerOperationEvent(newStaker, deferBlock); } // admin initiates a request that future ERC20 calls to trueUSD be delegated to _delegate function requestDelegation(DelegateERC20 _delegate) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); delegateOperation = DelegateOperation(_delegate, admin, deferBlock); DelegateOperationEvent(_delegate, deferBlock); } // admin initiates a request that incoming delegate* calls from _source be // accepted by trueUSD function requestDelegatedFrom(address _source) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); setDelegatedFromOperation = SetDelegatedFromOperation(_source, admin, deferBlock); SetDelegatedFromOperationEvent(_source, deferBlock); } // admin initiates a request that this contract's trueUSD pointer be updated to newContract function requestReplaceTrueUSD(TrueUSD newContract) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeTrueUSDOperation = ChangeTrueUSDOperation(newContract, admin, deferBlock); ChangeTrueUSDOperationEvent(newContract, deferBlock); } // admin initiates a request that trueUSD's name and symbol be changed function requestNameChange(string name, string symbol) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeNameOperation = ChangeNameOperation(name, symbol, admin, deferBlock); ChangeNameOperationEvent(name, symbol, deferBlock); } // after a day, admin finalizes mint request by providing the // index of the request (visible in the MintOperationEvent accompanying the original request) function finalizeMint(uint index) public onlyAdminOrOwner { MintOperation memory op = mintOperations[index]; require(op.admin == admin); //checks that the requester's adminship has not been revoked require(op.deferBlock <= block.number); //checks that enough time has elapsed address to = op.to; uint256 amount = op.amount; delete mintOperations[index]; trueUSD.mint(to, amount); } // after a day, admin finalizes the transfer of a child contract by providing the // index of the request (visible in the TransferChildOperationEvent accompanying the original request) function finalizeTransferChild(uint index) public onlyAdminOrOwner { TransferChildOperation memory op = transferChildOperations[index]; require(op.admin == admin); require(op.deferBlock <= block.number); Ownable _child = op.child; address _newOwner = op.newOwner; delete transferChildOperations[index]; _child.transferOwnership(_newOwner); } function finalizeReclaim(uint index) public onlyAdminOrOwner { ReclaimOperation memory op = reclaimOperations[index]; require(op.admin == admin); require(op.deferBlock <= block.number); Ownable other = op.other; delete reclaimOperations[index]; trueUSD.reclaimContract(other); } // after a day, admin finalizes the burn bounds change function finalizeChangeBurnBounds() public onlyAdminOrOwner { require(changeBurnBoundsOperation.admin == admin); require(changeBurnBoundsOperation.deferBlock <= block.number); uint newMin = changeBurnBoundsOperation.newMin; uint newMax = changeBurnBoundsOperation.newMax; delete changeBurnBoundsOperation; trueUSD.changeBurnBounds(newMin, newMax); } // after a day, admin finalizes the staking fee change function finalizeChangeStakingFees() public onlyAdminOrOwner { require(changeStakingFeesOperation.admin == admin); require(changeStakingFeesOperation.deferBlock <= block.number); uint80 _transferFeeNumerator = changeStakingFeesOperation._transferFeeNumerator; uint80 _transferFeeDenominator = changeStakingFeesOperation._transferFeeDenominator; uint80 _mintFeeNumerator = changeStakingFeesOperation._mintFeeNumerator; uint80 _mintFeeDenominator = changeStakingFeesOperation._mintFeeDenominator; uint256 _mintFeeFlat = changeStakingFeesOperation._mintFeeFlat; uint80 _burnFeeNumerator = changeStakingFeesOperation._burnFeeNumerator; uint80 _burnFeeDenominator = changeStakingFeesOperation._burnFeeDenominator; uint256 _burnFeeFlat = changeStakingFeesOperation._burnFeeFlat; delete changeStakingFeesOperation; trueUSD.changeStakingFees(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat); } // after a day, admin finalizes the staking fees recipient change function finalizeChangeStaker() public onlyAdminOrOwner { require(changeStakerOperation.admin == admin); require(changeStakerOperation.deferBlock <= block.number); address newStaker = changeStakerOperation.newStaker; delete changeStakerOperation; trueUSD.changeStaker(newStaker); } // after a day, admin finalizes the delegation function finalizeDelegation() public onlyAdminOrOwner { require(delegateOperation.admin == admin); require(delegateOperation.deferBlock <= block.number); DelegateERC20 delegate = delegateOperation.delegate; delete delegateOperation; trueUSD.delegateToNewContract(delegate); } function finalizeSetDelegatedFrom() public onlyAdminOrOwner { require(setDelegatedFromOperation.admin == admin); require(setDelegatedFromOperation.deferBlock <= block.number); address source = setDelegatedFromOperation.source; delete setDelegatedFromOperation; trueUSD.setDelegatedFrom(source); } function finalizeReplaceTrueUSD() public onlyAdminOrOwner { require(changeTrueUSDOperation.admin == admin); require(changeTrueUSDOperation.deferBlock <= block.number); TrueUSD newContract = changeTrueUSDOperation.newContract; delete changeTrueUSDOperation; trueUSD = newContract; } function finalizeChangeName() public onlyAdminOrOwner { require(changeNameOperation.admin == admin); require(changeNameOperation.deferBlock <= block.number); string memory name = changeNameOperation.name; string memory symbol = changeNameOperation.symbol; delete changeNameOperation; trueUSD.changeName(name, symbol); } // Owner of this contract (immediately) replaces the current admin with newAdmin function transferAdminship(address newAdmin) public onlyOwner { AdminshipTransferred(admin, newAdmin); admin = newAdmin; } // admin (immediately) updates a whitelist/blacklist function updateList(address list, address entry, bool flag) public onlyAdminOrOwner { AddressList(list).changeList(entry, flag); } function issueClaimOwnership(address _other) public onlyAdminOrOwner { Claimable other = Claimable(_other); other.claimOwnership(); } } contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } contract AllowanceSheet is Claimable { using SafeMath for uint256; mapping (address => mapping (address => uint256)) public allowanceOf; function addAllowance(address tokenHolder, address spender, uint256 value) public onlyOwner { allowanceOf[tokenHolder][spender] = allowanceOf[tokenHolder][spender].add(value); } function subAllowance(address tokenHolder, address spender, uint256 value) public onlyOwner { allowanceOf[tokenHolder][spender] = allowanceOf[tokenHolder][spender].sub(value); } function setAllowance(address tokenHolder, address spender, uint256 value) public onlyOwner { allowanceOf[tokenHolder][spender] = value; } } contract BalanceSheet is Claimable { using SafeMath for uint256; mapping (address => uint256) public balanceOf; function addBalance(address addr, uint256 value) public onlyOwner { balanceOf[addr] = balanceOf[addr].add(value); } function subBalance(address addr, uint256 value) public onlyOwner { balanceOf[addr] = balanceOf[addr].sub(value); } function setBalance(address addr, uint256 value) public onlyOwner { balanceOf[addr] = value; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic, Claimable { using SafeMath for uint256; BalanceSheet public balances; uint256 totalSupply_; function setBalanceSheet(address sheet) external onlyOwner { balances = BalanceSheet(sheet); balances.claimOwnership(); } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { transferAllArgsNoAllowance(msg.sender, _to, _value); return true; } function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal { require(_to != address(0)); require(_from != address(0)); require(_value <= balances.balanceOf(_from)); // SafeMath.sub will throw if there is not enough balance. balances.subBalance(_from, _value); balances.addBalance(_to, _value); Transfer(_from, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances.balanceOf(_owner); } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances.balanceOf(msg.sender)); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances.subBalance(burner, _value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract StandardToken is ERC20, BasicToken { AllowanceSheet public allowances; function setAllowanceSheet(address sheet) external onlyOwner { allowances = AllowanceSheet(sheet); allowances.claimOwnership(); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { transferAllArgsYesAllowance(_from, _to, _value, msg.sender); return true; } function transferAllArgsYesAllowance(address _from, address _to, uint256 _value, address spender) internal { require(_value <= allowances.allowanceOf(_from, spender)); allowances.subAllowance(_from, spender, _value); transferAllArgsNoAllowance(_from, _to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * 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 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { approveAllArgs(_spender, _value, msg.sender); return true; } function approveAllArgs(address _spender, uint256 _value, address _tokenHolder) internal { allowances.setAllowance(_tokenHolder, _spender, _value); Approval(_tokenHolder, _spender, _value); } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowances.allowanceOf(_owner, _spender); } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { increaseApprovalAllArgs(_spender, _addedValue, msg.sender); return true; } function increaseApprovalAllArgs(address _spender, uint _addedValue, address tokenHolder) internal { allowances.addAllowance(tokenHolder, _spender, _addedValue); Approval(tokenHolder, _spender, allowances.allowanceOf(tokenHolder, _spender)); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { decreaseApprovalAllArgs(_spender, _subtractedValue, msg.sender); return true; } function decreaseApprovalAllArgs(address _spender, uint _subtractedValue, address tokenHolder) internal { uint oldValue = allowances.allowanceOf(tokenHolder, _spender); if (_subtractedValue > oldValue) { allowances.setAllowance(tokenHolder, _spender, 0); } else { allowances.subAllowance(tokenHolder, _spender, _subtractedValue); } Approval(tokenHolder, _spender, allowances.allowanceOf(tokenHolder, _spender)); } } contract CanDelegate is StandardToken { // If this contract needs to be upgraded, the new contract will be stored // in 'delegate' and any ERC20 calls to this contract will be delegated to that one. DelegateERC20 public delegate; event DelegatedTo(address indexed newContract); // Can undelegate by passing in newContract = address(0) function delegateToNewContract(DelegateERC20 newContract) public onlyOwner { delegate = newContract; DelegatedTo(delegate); } // If a delegate has been designated, all ERC20 calls are forwarded to it function transfer(address to, uint256 value) public returns (bool) { if (delegate == address(0)) { return super.transfer(to, value); } else { return delegate.delegateTransfer(to, value, msg.sender); } } function transferFrom(address from, address to, uint256 value) public returns (bool) { if (delegate == address(0)) { return super.transferFrom(from, to, value); } else { return delegate.delegateTransferFrom(from, to, value, msg.sender); } } function balanceOf(address who) public view returns (uint256) { if (delegate == address(0)) { return super.balanceOf(who); } else { return delegate.delegateBalanceOf(who); } } function approve(address spender, uint256 value) public returns (bool) { if (delegate == address(0)) { return super.approve(spender, value); } else { return delegate.delegateApprove(spender, value, msg.sender); } } function allowance(address _owner, address spender) public view returns (uint256) { if (delegate == address(0)) { return super.allowance(_owner, spender); } else { return delegate.delegateAllowance(_owner, spender); } } function totalSupply() public view returns (uint256) { if (delegate == address(0)) { return super.totalSupply(); } else { return delegate.delegateTotalSupply(); } } function increaseApproval(address spender, uint addedValue) public returns (bool) { if (delegate == address(0)) { return super.increaseApproval(spender, addedValue); } else { return delegate.delegateIncreaseApproval(spender, addedValue, msg.sender); } } function decreaseApproval(address spender, uint subtractedValue) public returns (bool) { if (delegate == address(0)) { return super.decreaseApproval(spender, subtractedValue); } else { return delegate.delegateDecreaseApproval(spender, subtractedValue, msg.sender); } } } contract StandardDelegate is StandardToken, DelegateERC20 { address public delegatedFrom; modifier onlySender(address source) { require(msg.sender == source); _; } function setDelegatedFrom(address addr) onlyOwner public { delegatedFrom = addr; } // All delegate ERC20 functions are forwarded to corresponding normal functions function delegateTotalSupply() public view returns (uint256) { return totalSupply(); } function delegateBalanceOf(address who) public view returns (uint256) { return balanceOf(who); } function delegateTransfer(address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) { transferAllArgsNoAllowance(origSender, to, value); return true; } function delegateAllowance(address owner, address spender) public view returns (uint256) { return allowance(owner, spender); } function delegateTransferFrom(address from, address to, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) { transferAllArgsYesAllowance(from, to, value, origSender); return true; } function delegateApprove(address spender, uint256 value, address origSender) onlySender(delegatedFrom) public returns (bool) { approveAllArgs(spender, value, origSender); return true; } function delegateIncreaseApproval(address spender, uint addedValue, address origSender) onlySender(delegatedFrom) public returns (bool) { increaseApprovalAllArgs(spender, addedValue, origSender); return true; } function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) onlySender(delegatedFrom) public returns (bool) { decreaseApprovalAllArgs(spender, subtractedValue, origSender); return true; } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract TrueUSD is StandardDelegate, PausableToken, BurnableToken, NoOwner, CanDelegate { string public name = "TrueUSD"; string public symbol = "TUSD"; uint8 public constant decimals = 18; AddressList public canReceiveMintWhiteList; AddressList public canBurnWhiteList; AddressList public blackList; AddressList public noFeesList; uint256 public burnMin = 10000 * 10**uint256(decimals); uint256 public burnMax = 20000000 * 10**uint256(decimals); uint80 public transferFeeNumerator = 7; uint80 public transferFeeDenominator = 10000; uint80 public mintFeeNumerator = 0; uint80 public mintFeeDenominator = 10000; uint256 public mintFeeFlat = 0; uint80 public burnFeeNumerator = 0; uint80 public burnFeeDenominator = 10000; uint256 public burnFeeFlat = 0; address public staker; event ChangeBurnBoundsEvent(uint256 newMin, uint256 newMax); event Mint(address indexed to, uint256 amount); event WipedAccount(address indexed account, uint256 balance); function TrueUSD() public { totalSupply_ = 0; staker = msg.sender; } function setLists(AddressList _canReceiveMintWhiteList, AddressList _canBurnWhiteList, AddressList _blackList, AddressList _noFeesList) onlyOwner public { canReceiveMintWhiteList = _canReceiveMintWhiteList; canBurnWhiteList = _canBurnWhiteList; blackList = _blackList; noFeesList = _noFeesList; } function changeName(string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; } //Burning functions as withdrawing money from the system. The platform will keep track of who burns coins, //and will send them back the equivalent amount of money (rounded down to the nearest cent). function burn(uint256 _value) public { require(canBurnWhiteList.onList(msg.sender)); require(_value >= burnMin); require(_value <= burnMax); uint256 fee = payStakingFee(msg.sender, _value, burnFeeNumerator, burnFeeDenominator, burnFeeFlat, 0x0); uint256 remaining = _value.sub(fee); super.burn(remaining); } //Create _amount new tokens and transfer them to _to. //Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/MintableToken.sol function mint(address _to, uint256 _amount) onlyOwner public { require(canReceiveMintWhiteList.onList(_to)); totalSupply_ = totalSupply_.add(_amount); balances.addBalance(_to, _amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); payStakingFee(_to, _amount, mintFeeNumerator, mintFeeDenominator, mintFeeFlat, 0x0); } //Change the minimum and maximum amount that can be burned at once. Burning //may be disabled by setting both to 0 (this will not be done under normal //operation, but we can't add checks to disallow it without losing a lot of //flexibility since burning could also be as good as disabled //by setting the minimum extremely high, and we don't want to lock //in any particular cap for the minimum) function changeBurnBounds(uint newMin, uint newMax) onlyOwner public { require(newMin <= newMax); burnMin = newMin; burnMax = newMax; ChangeBurnBoundsEvent(newMin, newMax); } // transfer and transferFrom are both dispatched to this function, so we // check blacklist and pay staking fee here. function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal { require(!blackList.onList(_from)); require(!blackList.onList(_to)); super.transferAllArgsNoAllowance(_from, _to, _value); payStakingFee(_to, _value, transferFeeNumerator, transferFeeDenominator, 0, _from); } function wipeBlacklistedAccount(address account) public onlyOwner { require(blackList.onList(account)); uint256 oldValue = balanceOf(account); balances.setBalance(account, 0); totalSupply_ = totalSupply_.sub(oldValue); WipedAccount(account, oldValue); } function payStakingFee(address payer, uint256 value, uint80 numerator, uint80 denominator, uint256 flatRate, address otherParticipant) private returns (uint256) { if (noFeesList.onList(payer) || noFeesList.onList(otherParticipant)) { return 0; } uint256 stakingFee = value.mul(numerator).div(denominator).add(flatRate); if (stakingFee > 0) { super.transferAllArgsNoAllowance(payer, staker, stakingFee); } return stakingFee; } function changeStakingFees(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyOwner { require(_transferFeeDenominator != 0); require(_mintFeeDenominator != 0); require(_burnFeeDenominator != 0); transferFeeNumerator = _transferFeeNumerator; transferFeeDenominator = _transferFeeDenominator; mintFeeNumerator = _mintFeeNumerator; mintFeeDenominator = _mintFeeDenominator; mintFeeFlat = _mintFeeFlat; burnFeeNumerator = _burnFeeNumerator; burnFeeDenominator = _burnFeeDenominator; burnFeeFlat = _burnFeeFlat; } function changeStaker(address newStaker) public onlyOwner { require(newStaker != address(0)); staker = newStaker; } }
24 hours, assuming a 15 second blocktime. As long as this isn't too far off from reality it doesn't really matter.
contract TimeLockedController is HasNoEther, HasNoTokens, Claimable { using SafeMath for uint256; uint public constant blocksDelay = 24*60*60/15; struct MintOperation { address to; uint256 amount; address admin; uint deferBlock; } struct TransferChildOperation { Ownable child; address newOwner; address admin; uint deferBlock; } struct ReclaimOperation { Ownable other; address admin; uint deferBlock; } struct ChangeBurnBoundsOperation { uint newMin; uint newMax; address admin; uint deferBlock; } struct ChangeStakingFeesOperation { uint80 _transferFeeNumerator; uint80 _transferFeeDenominator; uint80 _mintFeeNumerator; uint80 _mintFeeDenominator; uint256 _mintFeeFlat; uint80 _burnFeeNumerator; uint80 _burnFeeDenominator; uint256 _burnFeeFlat; address admin; uint deferBlock; } struct ChangeStakerOperation { address newStaker; address admin; uint deferBlock; } struct DelegateOperation { DelegateERC20 delegate; address admin; uint deferBlock; } struct SetDelegatedFromOperation { address source; address admin; uint deferBlock; } struct ChangeTrueUSDOperation { TrueUSD newContract; address admin; uint deferBlock; } struct ChangeNameOperation { string name; string symbol; address admin; uint deferBlock; } address public admin; TrueUSD public trueUSD; MintOperation[] public mintOperations; TransferChildOperation[] public transferChildOperations; ReclaimOperation[] public reclaimOperations; ChangeBurnBoundsOperation public changeBurnBoundsOperation; ChangeStakingFeesOperation public changeStakingFeesOperation; ChangeStakerOperation public changeStakerOperation; DelegateOperation public delegateOperation; SetDelegatedFromOperation public setDelegatedFromOperation; ChangeTrueUSDOperation public changeTrueUSDOperation; ChangeNameOperation public changeNameOperation; modifier onlyAdminOrOwner() { require(msg.sender == admin || msg.sender == owner); _; } function computeDeferBlock() private view returns (uint) { if (msg.sender == owner) { return block.number; return block.number.add(blocksDelay); } } function computeDeferBlock() private view returns (uint) { if (msg.sender == owner) { return block.number; return block.number.add(blocksDelay); } } } else { function TimeLockedController(address _trueUSD) public { trueUSD = TrueUSD(_trueUSD); } event MintOperationEvent(address indexed _to, uint256 amount, uint deferBlock, uint opIndex); event TransferChildOperationEvent(address indexed _child, address indexed _newOwner, uint deferBlock, uint opIndex); event ReclaimOperationEvent(address indexed other, uint deferBlock, uint opIndex); event ChangeBurnBoundsOperationEvent(uint newMin, uint newMax, uint deferBlock); event ChangeStakingFeesOperationEvent(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat, uint deferBlock); event ChangeStakerOperationEvent(address newStaker, uint deferBlock); event DelegateOperationEvent(DelegateERC20 delegate, uint deferBlock); event SetDelegatedFromOperationEvent(address source, uint deferBlock); event ChangeTrueUSDOperationEvent(TrueUSD newContract, uint deferBlock); event ChangeNameOperationEvent(string name, string symbol, uint deferBlock); event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin); function requestMint(address _to, uint256 _amount) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); MintOperation memory op = MintOperation(_to, _amount, admin, deferBlock); MintOperationEvent(_to, _amount, deferBlock, mintOperations.length); mintOperations.push(op); } function requestTransferChild(Ownable _child, address _newOwner) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); TransferChildOperation memory op = TransferChildOperation(_child, _newOwner, admin, deferBlock); TransferChildOperationEvent(_child, _newOwner, deferBlock, transferChildOperations.length); transferChildOperations.push(op); } function requestReclaim(Ownable other) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); ReclaimOperation memory op = ReclaimOperation(other, admin, deferBlock); ReclaimOperationEvent(other, deferBlock, reclaimOperations.length); reclaimOperations.push(op); } function requestChangeBurnBounds(uint newMin, uint newMax) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeBurnBoundsOperation = ChangeBurnBoundsOperation(newMin, newMax, admin, deferBlock); ChangeBurnBoundsOperationEvent(newMin, newMax, deferBlock); } function requestChangeStakingFees(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeStakingFeesOperation = ChangeStakingFeesOperation(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat, admin, deferBlock); ChangeStakingFeesOperationEvent(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat, deferBlock); } function requestChangeStaker(address newStaker) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeStakerOperation = ChangeStakerOperation(newStaker, admin, deferBlock); ChangeStakerOperationEvent(newStaker, deferBlock); } function requestDelegation(DelegateERC20 _delegate) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); delegateOperation = DelegateOperation(_delegate, admin, deferBlock); DelegateOperationEvent(_delegate, deferBlock); } function requestDelegatedFrom(address _source) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); setDelegatedFromOperation = SetDelegatedFromOperation(_source, admin, deferBlock); SetDelegatedFromOperationEvent(_source, deferBlock); } function requestReplaceTrueUSD(TrueUSD newContract) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeTrueUSDOperation = ChangeTrueUSDOperation(newContract, admin, deferBlock); ChangeTrueUSDOperationEvent(newContract, deferBlock); } function requestNameChange(string name, string symbol) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeNameOperation = ChangeNameOperation(name, symbol, admin, deferBlock); ChangeNameOperationEvent(name, symbol, deferBlock); } function finalizeMint(uint index) public onlyAdminOrOwner { MintOperation memory op = mintOperations[index]; address to = op.to; uint256 amount = op.amount; delete mintOperations[index]; trueUSD.mint(to, amount); } function finalizeTransferChild(uint index) public onlyAdminOrOwner { TransferChildOperation memory op = transferChildOperations[index]; require(op.admin == admin); require(op.deferBlock <= block.number); Ownable _child = op.child; address _newOwner = op.newOwner; delete transferChildOperations[index]; _child.transferOwnership(_newOwner); } function finalizeReclaim(uint index) public onlyAdminOrOwner { ReclaimOperation memory op = reclaimOperations[index]; require(op.admin == admin); require(op.deferBlock <= block.number); Ownable other = op.other; delete reclaimOperations[index]; trueUSD.reclaimContract(other); } function finalizeChangeBurnBounds() public onlyAdminOrOwner { require(changeBurnBoundsOperation.admin == admin); require(changeBurnBoundsOperation.deferBlock <= block.number); uint newMin = changeBurnBoundsOperation.newMin; uint newMax = changeBurnBoundsOperation.newMax; delete changeBurnBoundsOperation; trueUSD.changeBurnBounds(newMin, newMax); } function finalizeChangeStakingFees() public onlyAdminOrOwner { require(changeStakingFeesOperation.admin == admin); require(changeStakingFeesOperation.deferBlock <= block.number); uint80 _transferFeeNumerator = changeStakingFeesOperation._transferFeeNumerator; uint80 _transferFeeDenominator = changeStakingFeesOperation._transferFeeDenominator; uint80 _mintFeeNumerator = changeStakingFeesOperation._mintFeeNumerator; uint80 _mintFeeDenominator = changeStakingFeesOperation._mintFeeDenominator; uint256 _mintFeeFlat = changeStakingFeesOperation._mintFeeFlat; uint80 _burnFeeNumerator = changeStakingFeesOperation._burnFeeNumerator; uint80 _burnFeeDenominator = changeStakingFeesOperation._burnFeeDenominator; uint256 _burnFeeFlat = changeStakingFeesOperation._burnFeeFlat; delete changeStakingFeesOperation; trueUSD.changeStakingFees(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat); } function finalizeChangeStaker() public onlyAdminOrOwner { require(changeStakerOperation.admin == admin); require(changeStakerOperation.deferBlock <= block.number); address newStaker = changeStakerOperation.newStaker; delete changeStakerOperation; trueUSD.changeStaker(newStaker); } function finalizeDelegation() public onlyAdminOrOwner { require(delegateOperation.admin == admin); require(delegateOperation.deferBlock <= block.number); DelegateERC20 delegate = delegateOperation.delegate; delete delegateOperation; trueUSD.delegateToNewContract(delegate); } function finalizeSetDelegatedFrom() public onlyAdminOrOwner { require(setDelegatedFromOperation.admin == admin); require(setDelegatedFromOperation.deferBlock <= block.number); address source = setDelegatedFromOperation.source; delete setDelegatedFromOperation; trueUSD.setDelegatedFrom(source); } function finalizeReplaceTrueUSD() public onlyAdminOrOwner { require(changeTrueUSDOperation.admin == admin); require(changeTrueUSDOperation.deferBlock <= block.number); TrueUSD newContract = changeTrueUSDOperation.newContract; delete changeTrueUSDOperation; trueUSD = newContract; } function finalizeChangeName() public onlyAdminOrOwner { require(changeNameOperation.admin == admin); require(changeNameOperation.deferBlock <= block.number); string memory name = changeNameOperation.name; string memory symbol = changeNameOperation.symbol; delete changeNameOperation; trueUSD.changeName(name, symbol); } function transferAdminship(address newAdmin) public onlyOwner { AdminshipTransferred(admin, newAdmin); admin = newAdmin; } function updateList(address list, address entry, bool flag) public onlyAdminOrOwner { AddressList(list).changeList(entry, flag); } function issueClaimOwnership(address _other) public onlyAdminOrOwner { Claimable other = Claimable(_other); other.claimOwnership(); } }
11,778,457
[ 1, 3247, 7507, 16, 15144, 279, 4711, 2205, 1203, 957, 18, 2970, 1525, 487, 333, 5177, 1404, 4885, 10247, 3397, 628, 2863, 560, 518, 3302, 1404, 8654, 15177, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2647, 8966, 2933, 353, 4393, 2279, 41, 1136, 16, 4393, 2279, 5157, 16, 18381, 429, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 1071, 5381, 4398, 6763, 273, 4248, 14, 4848, 14, 4848, 19, 3600, 31, 203, 203, 565, 1958, 490, 474, 2988, 288, 203, 3639, 1758, 358, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 1758, 3981, 31, 203, 3639, 2254, 2220, 1768, 31, 203, 565, 289, 203, 203, 565, 1958, 12279, 1763, 2988, 288, 203, 3639, 14223, 6914, 1151, 31, 203, 3639, 1758, 394, 5541, 31, 203, 3639, 1758, 3981, 31, 203, 3639, 2254, 2220, 1768, 31, 203, 565, 289, 203, 203, 565, 1958, 868, 14784, 2988, 288, 203, 3639, 14223, 6914, 1308, 31, 203, 3639, 1758, 3981, 31, 203, 3639, 2254, 2220, 1768, 31, 203, 565, 289, 203, 203, 565, 1958, 7576, 38, 321, 5694, 2988, 288, 203, 3639, 2254, 394, 2930, 31, 203, 3639, 2254, 394, 2747, 31, 203, 3639, 1758, 3981, 31, 203, 3639, 2254, 2220, 1768, 31, 203, 565, 289, 203, 203, 565, 1958, 7576, 510, 6159, 2954, 281, 2988, 288, 203, 3639, 2254, 3672, 389, 13866, 14667, 2578, 7385, 31, 203, 3639, 2254, 3672, 389, 13866, 14667, 8517, 26721, 31, 203, 3639, 2254, 3672, 389, 81, 474, 14667, 2578, 7385, 31, 203, 3639, 2254, 3672, 389, 81, 474, 14667, 8517, 26721, 31, 203, 3639, 2254, 5034, 389, 81, 474, 14667, 16384, 31, 203, 3639, 2254, 3672, 389, 70, 321, 14667, 2578, 7385, 31, 203, 3639, 2254, 3672, 389, 70, 2 ]
pragma solidity ^0.4.24; contract BO3Kevents { event onBuying ( address indexed _addr, uint256 ethAmount, uint256 flagAmount, uint256 playerFlags, uint256 ethOfRound, uint256 keysOfRound, uint256 potOfRound ); event onTimeAdding( uint256 startTime, uint256 endTime, uint256 newTimeInterval, uint256 currentInterval ); event onDiscount( address indexed _addr, uint256 randomValue, uint256 discountValue, bool getDiscount ); event onRoundEnding( address indexed winnerAddr, uint teamID, uint256 winValue, uint256 soldierValue, uint256 teamValue, uint256 nextRoundStartTime, uint256 nextRoundEndTime, uint256 nextRoundPot ); event onWithdraw( address indexed withdrawAddr, uint256 discountRevenue, uint256 refferedRevenue, uint256 winRevenue, uint256 flagRevenue ); } contract modularLong is BO3Kevents {} contract BO3KMain is modularLong { using SafeMath for *; using BO3KCalcLong for uint256; address constant public Admin = 0x3ac98F5Ea4946f58439d551E20Ed12091AF0F597; uint256 constant public LEADER_FEE = 0.03 ether; uint256 private adminFee = 0; uint256 private adminRevenue = 0; uint256 private winTeamValue = 0; uint private winTeamID = 0; string constant public name = "Blockchain of 3 Kindoms"; string constant public symbol = "BO3K"; uint256 constant private DISCOUNT_PROB = 200; uint256 constant private DISCOUNT_VALUE_5PER_OFF = 50; uint256 constant private DISCOUNT_VALUE_10PER_OFF = 100; uint256 constant private DISCOUNT_VALUE_15PER_OFF = 150; uint256 constant private DENOMINATOR = 1000; uint256 constant private _nextRoundSettingTime = 0 minutes; uint256 constant private _flagBuyingInterval = 30 seconds; uint256 constant private _maxDuration = 24 hours; uint256 constant private _officerCommission = 150; bool _activated = false; bool CoolingMutex = false; uint256 public roundID; uint public _teamID; BO3Kdatasets.PotSplit potSplit; BO3Kdatasets.FlagInfo Flag; mapping (uint256 => BO3Kdatasets.Team) team; mapping (uint256 => mapping (uint256 => BO3Kdatasets.TeamData) ) teamData; mapping (uint256 => BO3Kdatasets.Round) round; mapping (uint256 => mapping (address => BO3Kdatasets.Player) ) player; mapping (address => uint256) playerFlags; constructor () public { team[1] = BO3Kdatasets.Team(0, 500, 250, 150, 50, 50, 0, 0 ); team[2] = BO3Kdatasets.Team(1, 250, 500, 150, 50, 50, 0, 0 ); team[3] = BO3Kdatasets.Team(2, 375, 375, 150, 50, 50, 0, 0 ); potSplit = BO3Kdatasets.PotSplit(450, 450, 50, 50); // to-do: formation of flag and time update Flag = BO3Kdatasets.FlagInfo( 10000000000000000, now ); } modifier isActivated() { require ( _activated == true, "Did not activated" ); _; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; // size of the code at address _addre assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "Addresses not owned by human are forbidden"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 100000000000, "ground limit"); require(_eth <= 100000000000000000000000, "floor limit"); _; } modifier isPlayerRegistered(uint256 _roundID, address _addr) { require (player[_roundID][_addr].hasRegistered, "The Player Has Not Registered!"); _; } function buyFlag( uint _tID, address refferedAddr ) isActivated() isHuman() isWithinLimits(msg.value) public payable { require( _tID == 1 || _tID == 2 || _tID == 3 , "Invalid Team ID!" ); // core( msg.sender, msg.value, _teamID ); uint256 _now = now; _teamID = _tID; // if it's around the legal time if( isLegalTime( _now ) ) { // main logic of buying uint256 flagAmount = buyCore( refferedAddr ); // 30 sec interval updateTimer( flagAmount ); } else { if( !isLegalTime( _now ) && round[roundID].ended == false ) { round[roundID].ended = true; endRound(); } else { revert(); } // to-do:rcountdown for 1 hour to cool down } } function buyCore( address refferedAddr) isActivated() isWithinLimits( msg.value ) private returns( uint256 ) { // flag formula if( player[roundID][refferedAddr].isGeneral == false ) { refferedAddr = address(0); } address _addr = msg.sender; uint256 _value = msg.value; uint256 flagAmount = (round[roundID].totalEth).keysRec( _value ); require ( flagAmount >= 10 ** 18, "At least 1 whole flag" ); // discount info bool getDiscount = false; // update data of the round, contains total eth, total flags, and pot value round[roundID].totalEth = ( round[roundID].totalEth ).add( _value ); round[roundID].totalFlags = ( round[roundID].totalFlags ).add( flagAmount ); // distribute value to the pot of the round. 50%, 25%, 37.5%, respectively round[roundID].pot = ( round[roundID].pot ).add( ( _value.mul( team[_teamID].city ) ).div( DENOMINATOR ) ); // update data of the team, contains total eth, total flags team[_teamID].totalEth = ( team[_teamID].totalEth ).add( _value ); team[_teamID].totalFlags = ( team[_teamID].totalFlags ).add( flagAmount ); teamData[roundID][_teamID].totalEth = ( teamData[roundID][_teamID].totalEth ).add( _value ); teamData[roundID][_teamID].totalFlags = ( teamData[roundID][_teamID].totalFlags ).add( flagAmount ); // if the user has participated in before, just add the total flag to the player if( player[roundID][_addr].hasRegistered ) { player[roundID][_addr].flags += flagAmount; } else { // user data player[roundID][_addr] = BO3Kdatasets.Player({ addr: _addr, flags: flagAmount, win: 0, refferedRevenue: 0, discountRevenue: 0, teamID: _teamID, generalID: 0, payMask: 0, hasRegistered: true, isGeneral: false, isWithdrawed: false }); } // player's flags playerFlags[_addr] += flagAmount; // winner ID of the round round[roundID].playerID = _addr; // random discount uint256 randomValue = random(); uint256 discountValue = 0; // discount judgement if( randomValue < team[_teamID].grain ) { if( _value >= 10 ** 17 && _value < 10 ** 18 ) { discountValue = (_value.mul( DISCOUNT_VALUE_5PER_OFF )).div( DENOMINATOR ); } else if( _value >= 10 ** 18 && _value < 10 ** 19 ) { discountValue = (_value.mul( DISCOUNT_VALUE_10PER_OFF )).div( DENOMINATOR ); } else if( _value >= 10 ** 19 ) { discountValue = (_value.mul( DISCOUNT_VALUE_15PER_OFF )).div( DENOMINATOR ); } // _addr.transfer( discountValue ); // add to win bonus if getting discount player[roundID][_addr].discountRevenue = (player[roundID][_addr].discountRevenue).add( discountValue ); getDiscount = true; } // distribute the eth values // the distribution ratio differs from reffered address uint256 soldierEarn; // flag distribution if( refferedAddr != address(0) && refferedAddr != _addr ) { // 25%, 50%, 37.5% for soldier, respectively soldierEarn = (((_value.mul( team[_teamID].soldier ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags)).mul(flagAmount)/ (1000000000000000000); // 5% for admin adminFee += ( _value.mul( team[_teamID].teamWelfare ) ).div( DENOMINATOR ); // 15% for officer player[roundID][refferedAddr].refferedRevenue += ( _value.mul( team[_teamID].officer ) ).div( DENOMINATOR ); // paymask round[roundID].payMask += ( (_value.mul( team[_teamID].soldier ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags); player[roundID][_addr].payMask = ((( (round[roundID].payMask).mul( flagAmount )) / (1000000000000000000)).sub(soldierEarn)).add(player[roundID][_addr].payMask); } else { // 40%, 65%, 52.5% for soldier, respectively soldierEarn = (((_value.mul( team[_teamID].soldier + team[_teamID].officer ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags)).mul(flagAmount)/ (1000000000000000000); // 5% for admin adminFee += ( _value.mul( team[_teamID].teamWelfare ) ).div( DENOMINATOR ); // paymask round[roundID].payMask += ( (_value.mul( team[_teamID].soldier + team[_teamID].officer ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags); player[roundID][_addr].payMask = ((( (round[roundID].payMask).mul( flagAmount )) / (1000000000000000000)).sub(soldierEarn)).add(player[roundID][_addr].payMask); } emit BO3Kevents.onDiscount( _addr, randomValue, discountValue, getDiscount ); emit BO3Kevents.onBuying( _addr, _value, flagAmount, playerFlags[_addr], round[roundID].totalEth, round[roundID].totalFlags, round[roundID].pot ); return flagAmount; } function updateTimer( uint256 flagAmount ) private { uint256 _now = now; // uint256 newTimeInterval = ( round[roundID].end ).add( _flagBuyingInterval ).sub( _now ); uint256 newTimeInterval = ( round[roundID].end ).add( flagAmount.div(1000000000000000000).mul(10) ).sub( _now ); if( newTimeInterval > _maxDuration ) { newTimeInterval = _maxDuration; } round[roundID].end = ( _now ).add( newTimeInterval ); round[roundID].updatedTimeRounds = (round[roundID].updatedTimeRounds).add(flagAmount.div(1000000000000000000)); emit BO3Kevents.onTimeAdding( round[roundID].start, round[roundID].end, newTimeInterval, ( round[roundID].end ).sub( _now ) ); } function endRound() isActivated() private { // end round: get winner ID, team ID, pot, and values, respectively require ( !isLegalTime(now), "The round has not finished" ); address winnerPlayerID = round[roundID].playerID; uint winnerTeamID = player[roundID][winnerPlayerID].teamID; uint256 potValue = round[roundID].pot; uint256 winValue = ( potValue.mul( potSplit._winRatio ) ).div( DENOMINATOR ); uint256 soldierValue = ( potValue.mul( potSplit._soldiersRatio ) ).div( DENOMINATOR ); uint256 nextRoundValue = ( potValue.mul( potSplit._nextRatio ) ).div( DENOMINATOR ); uint256 adminValue = ( potValue.mul( potSplit._adminRatio ) ).div( DENOMINATOR ); uint256 teamValue = team[winnerTeamID].totalEth; if( winnerPlayerID == address(0x0) ) { Admin.transfer( potValue ); nextRoundValue -= nextRoundValue; adminValue -= adminValue; } else { player[roundID][winnerPlayerID].win = ( player[roundID][winnerPlayerID].win ).add( winValue ); winTeamID = winnerTeamID; } // Admin.transfer( adminValue + adminFee ); adminRevenue = adminRevenue.add( adminValue ).add( adminFee ); adminFee -= adminFee; round[roundID].ended = true; roundID++; round[roundID].start = now.add( _nextRoundSettingTime ); round[roundID].end = (round[roundID].start).add( _maxDuration ); round[roundID].pot = nextRoundValue; emit BO3Kevents.onRoundEnding( winnerPlayerID, winnerTeamID, winValue, soldierValue, teamValue, round[roundID].start, round[roundID].end, round[roundID].pot ); } function activate() public { //activation require ( msg.sender == 0xABb29fd841c9B919c3B681194c6173f30Ff7055D, "msg sender error" ); require ( _activated == false, "Has activated" ); _activated = true; roundID = 1; round[roundID].start = now; round[roundID].end = round[roundID].start + _maxDuration; round[roundID].ended = false; round[roundID].updatedTimeRounds = 0; } /* * * other functions * */ // next flag value function getFlagPrice() public view returns( uint256 ) { // return ( ((round[roundID].totalFlags).add(1000000000000000000)).ethRec(1000000000000000000) ); uint256 _now = now; if( isLegalTime( _now ) ) { return ( ((round[roundID].totalFlags).add( 1000000000000000000 )).ethRec( 1000000000000000000 ) ); } else { return (75000000000000); } } function getFlagPriceByFlags (uint256 _roundID, uint256 _flagAmount) public view returns (uint256) { return round[_roundID].totalFlags.add(_flagAmount.mul( 10 ** 18 )).ethRec(_flagAmount.mul( 10 ** 18 )); } function getRemainTime() isActivated() public view returns( uint256 ) { return ( (round[roundID].start).sub( now ) ); } function isLegalTime( uint256 _now ) internal view returns( bool ) { return ( _now >= round[roundID].start && _now <= round[roundID].end ); } function isLegalTime() public view returns( bool ) { uint256 _now = now; return ( _now >= round[roundID].start && _now <= round[roundID].end ); } function random() internal view returns( uint256 ) { return uint256( uint256( keccak256( block.timestamp, block.difficulty ) ) % DENOMINATOR ); } function withdraw( uint256 _roundID ) isActivated() isHuman() public { require ( player[_roundID][msg.sender].hasRegistered == true, "Not Registered Before" ); uint256 _discountRevenue = player[_roundID][msg.sender].discountRevenue; uint256 _refferedRevenue = player[_roundID][msg.sender].refferedRevenue; uint256 _winRevenue = player[_roundID][msg.sender].win; uint256 _flagRevenue = getFlagRevenue( _roundID ) ; if( isLegalTime( now ) && !round[_roundID].ended ) { // to-do: withdraw function msg.sender.transfer( _discountRevenue + _refferedRevenue + _winRevenue + _flagRevenue ); } else { msg.sender.transfer( getTeamBonus(_roundID) + _discountRevenue + _refferedRevenue + _winRevenue + _flagRevenue ); } player[_roundID][msg.sender].discountRevenue = 0; player[_roundID][msg.sender].refferedRevenue = 0; player[_roundID][msg.sender].win = 0; player[_roundID][msg.sender].payMask = _flagRevenue.add(player[_roundID][msg.sender].payMask); // if( round[_roundID].ended ) { // player[_roundID][msg.sender].flags = 0; // } player[_roundID][msg.sender].isWithdrawed = true; emit BO3Kevents.onWithdraw( msg.sender, _discountRevenue, _refferedRevenue, _winRevenue, _flagRevenue ); } function becomeGeneral( uint _generalID ) public payable { require( msg.value >= LEADER_FEE && player[roundID][msg.sender].hasRegistered, "Not enough money or not player" ); msg.sender.transfer( LEADER_FEE ); player[roundID][msg.sender].isGeneral = true; player[roundID][msg.sender].generalID = _generalID; } /* * Getters for Website */ function getIsActive () public view returns (bool) { return _activated; } function getPot (uint256 _roundID) public view returns (uint256) { return round[_roundID].pot; } function getTime (uint256 _roundID) public view returns (uint256, uint256) { if( isLegalTime( now ) ) { return (round[_roundID].start, (round[_roundID].end).sub( now ) ); } else { return (0, 0); } } function getTeam (uint256 _roundID) public view returns (uint) { return player[_roundID][msg.sender].teamID; } function getTeamData (uint256 _roundID, uint _tID) public view returns (uint256, uint256) { return (teamData[_roundID][_tID].totalFlags, teamData[_roundID][_tID].totalEth); } function getTeamBonus (uint256 _roundID) public view returns (uint256) { // pot * 0.45 * (playerflag/teamflag) uint256 potValue = round[_roundID].pot; uint256 _winValue = ( potValue.mul( potSplit._soldiersRatio ) ).div( DENOMINATOR ); uint _tID = player[_roundID][msg.sender].teamID; if( isLegalTime( now ) && (_roundID == roundID)) { // return ((player[_roundID][msg.sender].flags).mul(_winValue)).div( team[_tID].totalFlags ); return ((player[_roundID][msg.sender].flags).mul(_winValue)).div( teamData[_roundID][_tID].totalFlags ); } else { if( _tID != winTeamID ) { return 0; } else if (player[_roundID][msg.sender].isWithdrawed) { return 0; } else { // return ((player[_roundID][msg.sender].flags).mul(_winValue)).div( team[_tID].totalFlags ); return ((player[_roundID][msg.sender].flags).mul(_winValue)).div( teamData[_roundID][_tID].totalFlags ); } } } function getBonus (uint256 _roundID) public view returns (uint256) { return player[_roundID][msg.sender].discountRevenue + player[_roundID][msg.sender].win; } function getAllRevenue (uint256 _roundID) public view returns (uint256) { return (getTeamBonus(_roundID) + player[_roundID][msg.sender].discountRevenue + player[_roundID][msg.sender].win + getFlagRevenue(_roundID) + player[_roundID][msg.sender].refferedRevenue) ; } function getAllWithdrawableRevenue (uint256 _roundID) public view returns (uint256) { if( isLegalTime(now) && ( _roundID == roundID ) ) return (player[_roundID][msg.sender].discountRevenue + player[_roundID][msg.sender].win + getFlagRevenue(_roundID) + player[_roundID][msg.sender].refferedRevenue) ; return (getTeamBonus(_roundID) + player[_roundID][msg.sender].discountRevenue + player[_roundID][msg.sender].win + getFlagRevenue(_roundID) + player[_roundID][msg.sender].refferedRevenue) ; } function getFlagRevenue(uint _round) public view returns(uint256) { return((((player[_round][msg.sender].flags).mul(round[_round].payMask)) / (1000000000000000000)).sub(player[_round][msg.sender].payMask)); // return((((round[_round].payMask).mul(player[_round][msg.sender].flags)) / (1000000000000000000)).sub(player[_round][msg.sender].payMask)); } function getGeneralProfit (uint256 _roundID) public view returns (uint256) { return player[_roundID][msg.sender].refferedRevenue; } function getDistributedETH (uint256 _roundID) public view returns (uint256) { return (round[_roundID].totalEth).sub(round[_roundID].pot).sub(adminFee); } function getGeneral (uint256 _roundID) public view returns (bool, uint) { return (player[_roundID][msg.sender].isGeneral, player[_roundID][msg.sender].generalID); } function getPlayerFlagAmount (uint256 _roundID) public view returns (uint256) { return player[_roundID][msg.sender].flags; } function getTotalFlagAmount (uint256 _roundID) public view returns (uint256) { return round[_roundID].totalFlags; } function getTotalEth (uint256 _roundID) public view returns (uint256) { return round[_roundID].totalEth; } function getUpdatedTime (uint256 _roundID) public view returns (uint) { return round[_roundID].updatedTimeRounds; } function getRoundData( uint256 _roundID ) public view returns( address, uint256, uint256, bool ) { return ( round[_roundID].playerID, round[_roundID].pot, round[_roundID].totalEth, round[_roundID].ended ); } /* admin */ function getAdminRevenue () public view returns (uint) { return adminRevenue; } function withdrawAdminRevenue() public { require (msg.sender == Admin ); Admin.transfer( adminRevenue ); adminRevenue = 0; } } library BO3KCalcLong { using SafeMath for *; function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256){ return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } /** * The BO3Kdatasets library does this and that... */ library BO3Kdatasets { struct Team { uint teamID; uint256 city; uint256 soldier; uint256 officer; uint256 grain; uint256 teamWelfare; uint256 totalEth; uint256 totalFlags; } struct TeamData { uint256 totalEth; uint256 totalFlags; } struct PotSplit { uint256 _winRatio; uint256 _soldiersRatio; uint256 _nextRatio; uint256 _adminRatio; } struct Round { address playerID; // pID of player in lead // uint256 teamID; // tID of team in lead uint256 start; // time round started uint256 end; // time ends/ended uint256 totalFlags; // keys uint256 totalEth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 payMask; uint updatedTimeRounds; bool ended; // has round end function been ran } struct Player { address addr; // player uint256 flags; // flags uint256 win; // winnings vault uint256 refferedRevenue; uint256 discountRevenue; uint256 payMask; uint teamID; bool hasRegistered; bool isGeneral; uint generalID; bool isWithdrawed; } struct FlagInfo { uint256 _flagValue; uint256 updateTime; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; require(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
flag formula if the user has participated in before, just add the total flag to the player user data discount judgement flag distribution 25%, 50%, 37.5% for soldier, respectively 5% for admin 15% for officer paymask 40%, 65%, 52.5% for soldier, respectively 5% for admin paymask
function buyCore( address refferedAddr) isActivated() isWithinLimits( msg.value ) private returns( uint256 ) { if( player[roundID][refferedAddr].isGeneral == false ) { refferedAddr = address(0); } address _addr = msg.sender; uint256 _value = msg.value; uint256 flagAmount = (round[roundID].totalEth).keysRec( _value ); require ( flagAmount >= 10 ** 18, "At least 1 whole flag" ); round[roundID].totalFlags = ( round[roundID].totalFlags ).add( flagAmount ); team[_teamID].totalFlags = ( team[_teamID].totalFlags ).add( flagAmount ); teamData[roundID][_teamID].totalEth = ( teamData[roundID][_teamID].totalEth ).add( _value ); teamData[roundID][_teamID].totalFlags = ( teamData[roundID][_teamID].totalFlags ).add( flagAmount ); if( player[roundID][_addr].hasRegistered ) { player[roundID][_addr].flags += flagAmount; player[roundID][_addr] = BO3Kdatasets.Player({ addr: _addr, flags: flagAmount, win: 0, refferedRevenue: 0, discountRevenue: 0, teamID: _teamID, generalID: 0, payMask: 0, hasRegistered: true, isGeneral: false, isWithdrawed: false }); } uint256 discountValue = 0; if( randomValue < team[_teamID].grain ) { if( _value >= 10 ** 17 && _value < 10 ** 18 ) { discountValue = (_value.mul( DISCOUNT_VALUE_5PER_OFF )).div( DENOMINATOR ); discountValue = (_value.mul( DISCOUNT_VALUE_10PER_OFF )).div( DENOMINATOR ); discountValue = (_value.mul( DISCOUNT_VALUE_15PER_OFF )).div( DENOMINATOR ); } getDiscount = true; } if( refferedAddr != address(0) && refferedAddr != _addr ) { soldierEarn = (((_value.mul( team[_teamID].soldier ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags)).mul(flagAmount)/ (1000000000000000000); adminFee += ( _value.mul( team[_teamID].teamWelfare ) ).div( DENOMINATOR ); player[roundID][refferedAddr].refferedRevenue += ( _value.mul( team[_teamID].officer ) ).div( DENOMINATOR ); round[roundID].payMask += ( (_value.mul( team[_teamID].soldier ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags); player[roundID][_addr].payMask = ((( (round[roundID].payMask).mul( flagAmount )) / (1000000000000000000)).sub(soldierEarn)).add(player[roundID][_addr].payMask); soldierEarn = (((_value.mul( team[_teamID].soldier + team[_teamID].officer ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags)).mul(flagAmount)/ (1000000000000000000); adminFee += ( _value.mul( team[_teamID].teamWelfare ) ).div( DENOMINATOR ); round[roundID].payMask += ( (_value.mul( team[_teamID].soldier + team[_teamID].officer ) / DENOMINATOR).mul(1000000000000000000)) / (round[roundID].totalFlags); player[roundID][_addr].payMask = ((( (round[roundID].payMask).mul( flagAmount )) / (1000000000000000000)).sub(soldierEarn)).add(player[roundID][_addr].payMask); } emit BO3Kevents.onDiscount( _addr, randomValue, discountValue, getDiscount ); emit BO3Kevents.onBuying( _addr, _value, flagAmount, playerFlags[_addr], round[roundID].totalEth, round[roundID].totalFlags, round[roundID].pot ); return flagAmount; }
5,363,136
[ 1, 6420, 8013, 309, 326, 729, 711, 30891, 690, 316, 1865, 16, 2537, 527, 326, 2078, 2982, 358, 326, 7291, 729, 501, 12137, 525, 1100, 75, 820, 2982, 7006, 6969, 9, 16, 6437, 9, 16, 18091, 18, 25, 9, 364, 272, 1673, 2453, 16, 19629, 1381, 9, 364, 3981, 4711, 9, 364, 3397, 21349, 8843, 4455, 8063, 9, 16, 15892, 9, 16, 18106, 18, 25, 9, 364, 272, 1673, 2453, 16, 19629, 1381, 9, 364, 3981, 8843, 4455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 30143, 4670, 12, 1758, 1278, 586, 329, 3178, 13, 353, 28724, 1435, 353, 18949, 12768, 12, 1234, 18, 1132, 262, 3238, 1135, 12, 2254, 5034, 262, 288, 203, 1082, 203, 202, 202, 430, 12, 7291, 63, 2260, 734, 6362, 1734, 586, 329, 3178, 8009, 291, 12580, 422, 629, 262, 288, 203, 1082, 202, 1734, 586, 329, 3178, 273, 1758, 12, 20, 1769, 203, 202, 202, 97, 203, 203, 202, 202, 2867, 389, 4793, 273, 1234, 18, 15330, 31, 203, 202, 202, 11890, 5034, 389, 1132, 273, 1234, 18, 1132, 31, 203, 203, 202, 202, 11890, 5034, 2982, 6275, 273, 261, 2260, 63, 2260, 734, 8009, 4963, 41, 451, 2934, 2452, 5650, 12, 389, 1132, 11272, 203, 202, 202, 6528, 261, 2982, 6275, 1545, 1728, 2826, 6549, 16, 315, 861, 4520, 404, 7339, 2982, 6, 11272, 203, 203, 203, 202, 202, 2260, 63, 2260, 734, 8009, 4963, 5094, 273, 261, 3643, 63, 2260, 734, 8009, 4963, 5094, 262, 18, 1289, 12, 2982, 6275, 11272, 203, 203, 203, 202, 202, 10035, 63, 67, 10035, 734, 8009, 4963, 5094, 273, 261, 5927, 63, 67, 10035, 734, 8009, 4963, 5094, 262, 18, 1289, 12, 2982, 6275, 11272, 203, 203, 202, 202, 10035, 751, 63, 2260, 734, 6362, 67, 10035, 734, 8009, 4963, 41, 451, 273, 261, 5927, 751, 63, 2260, 734, 6362, 67, 10035, 734, 8009, 4963, 41, 451, 262, 18, 1289, 12, 389, 1132, 11272, 203, 202, 202, 10035, 751, 63, 2260, 734, 6362, 67, 10035, 734, 8009, 4963, 5094, 273, 261, 5927, 751, 63, 2 ]
/* version metahash ETH multi sign wallet 0.1.5 RC */ pragma solidity ^0.4.18; contract mhethkeeper { /* contract settings */ /* dynamic data section */ address public recipient; /* recipient */ uint256 public amountToTransfer; /* quantity */ /* static data section */ bool public isFinalized; /* settings are finalized */ uint public minVotes; /* minimum amount of votes */ uint public curVotes; /* current amount of votes */ address public owner; /* contract creator */ uint public mgrCount; /* number of managers */ mapping (uint => bool) public mgrVotes; /* managers votes */ mapping (uint => address) public mgrAddress; /* managers address */ /* constructor */ function mhethkeeper() public{ owner = msg.sender; isFinalized = false; curVotes = 0; mgrCount = 0; minVotes = 2; } /* add a wallet manager */ function AddManager(address _manager) public{ if (!isFinalized && (msg.sender == owner)){ mgrCount = mgrCount + 1; mgrAddress[mgrCount] = _manager; mgrVotes[mgrCount] = false; } else { revert(); } } /* finalize settings */ function Finalize() public{ if (!isFinalized && (msg.sender == owner)){ isFinalized = true; } else { revert(); } } /* set a new action and set a value of zero on a vote */ function SetAction(address _recipient, uint256 _amountToTransfer) public{ if (!isFinalized){ revert(); } if (IsManager(msg.sender)){ if (this.balance < _amountToTransfer){ revert(); } recipient = _recipient; amountToTransfer = _amountToTransfer; for (uint i = 1; i <= mgrCount; i++) { mgrVotes[i] = false; } curVotes = 0; } else { revert(); } } /* manager votes for the action */ function Approve(address _recipient, uint256 _amountToTransfer) public{ if (!isFinalized){ revert(); } if (!((recipient == _recipient) && (amountToTransfer == _amountToTransfer))){ revert(); } for (uint i = 1; i <= mgrCount; i++) { if (mgrAddress[i] == msg.sender){ if (!mgrVotes[i]){ mgrVotes[i] = true; curVotes = curVotes + 1; if (curVotes >= minVotes){ recipient.transfer(amountToTransfer); NullSettings(); } } else { revert(); } } } } /* set a default payable function */ function () public payable {} /* set default empty settings */ function NullSettings() private{ recipient = address(0x0); amountToTransfer = 0; curVotes = 0; for (uint i = 1; i <= mgrCount; i++) { mgrVotes[i] = false; } } /* check that the sender is a manager */ function IsManager(address _manager) private view returns(bool){ for (uint i = 1; i <= mgrCount; i++) { if (mgrAddress[i] == _manager){ return true; } } return false; } }
finalize settings */
function Finalize() public{ if (!isFinalized && (msg.sender == owner)){ isFinalized = true; revert(); } }
15,835,725
[ 1, 30343, 1947, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30740, 1435, 1071, 95, 203, 3639, 309, 16051, 291, 7951, 1235, 597, 261, 3576, 18, 15330, 422, 3410, 3719, 95, 203, 5411, 29200, 1235, 273, 638, 31, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/OrderValidator.sol
* @title OrderValidator @author 0age @notice OrderValidator contains functionality related to validating orders and updating their status./ Track status of each order (validated, cancelled, and fraction filled). Track nonces for contract offerers.
contract OrderValidator is Executor, ZoneInteraction { mapping(bytes32 => OrderStatus) private _orderStatus; mapping(address => uint256) internal _contractNonces; function _validateBasicOrderAndUpdateStatus( bytes32 orderHash, bytes calldata signature constructor(address conduitController) Executor(conduitController) {} ) internal { address offerer; assembly { offerer := calldataload(BasicOrder_offerer_cdPtr) } orderHash, orderStatus, ); if (!orderStatus.isValidated) { _verifySignature(offerer, orderHash, signature); } orderStatus.isCancelled = false; orderStatus.numerator = 1; orderStatus.denominator = 1; } ) internal { address offerer; assembly { offerer := calldataload(BasicOrder_offerer_cdPtr) } orderHash, orderStatus, ); if (!orderStatus.isValidated) { _verifySignature(offerer, orderHash, signature); } orderStatus.isCancelled = false; orderStatus.numerator = 1; orderStatus.denominator = 1; } OrderStatus storage orderStatus = _orderStatus[orderHash]; _verifyOrderStatus( ) internal { address offerer; assembly { offerer := calldataload(BasicOrder_offerer_cdPtr) } orderHash, orderStatus, ); if (!orderStatus.isValidated) { _verifySignature(offerer, orderHash, signature); } orderStatus.isCancelled = false; orderStatus.numerator = 1; orderStatus.denominator = 1; } orderStatus.isValidated = true; function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } bool invalidFraction; function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } return function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } if ( function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } orderHash = _assertConsiderationLengthAndGetOrderHash(orderParameters); OrderStatus storage orderStatus = _orderStatus[orderHash]; if ( function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } } 1 { } { function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } filledNumerator := and( function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } filledNumerator := mul(filledNumerator, denominator) filledNumerator := add(numerator, filledNumerator) let carry := mul( if or( function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } } _b { } { let safeScaleDown := add(scaleDown, iszero(scaleDown)) numerator := div(numerator, safeScaleDown) if or( function _validateOrderAndUpdateStatus( AdvancedOrder memory advancedOrder, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { OrderParameters memory orderParameters = advancedOrder.parameters; if ( !_verifyTime( orderParameters.startTime, orderParameters.endTime, revertOnInvalid ) ) { return (bytes32(0), 0, 0); } assembly { numerator := and( mload(add(advancedOrder, AdvancedOrder_numerator_offset)), MaxUint120 ) denominator := and( mload(add(advancedOrder, AdvancedOrder_denominator_offset)), MaxUint120 ) } if (orderParameters.orderType == OrderType.CONTRACT) { assembly { invalidFraction := xor(mul(numerator, denominator), 1) } if (invalidFraction) { _revertBadFraction(); } _getGeneratedOrder( orderParameters, advancedOrder.extraData, revertOnInvalid ); } assembly { invalidFraction := or(gt(numerator, denominator), iszero(numerator)) } if (invalidFraction) { _revertBadFraction(); } _doesNotSupportPartialFills( orderParameters.orderType, numerator, denominator ) ) { _revertPartialFillsNotEnabledForOrder(); } !_verifyOrderStatus( orderHash, orderStatus, revertOnInvalid ) ) { return (orderHash, 0, 0); } if (!orderStatus.isValidated) { _verifySignature( orderParameters.offerer, orderHash, advancedOrder.signature ); } assembly { let orderStatusSlot := orderStatus.slot let filledNumerator := sload(orderStatusSlot) let filledDenominator := shr( OrderStatus_filledDenominator_offset, filledNumerator ) for { if iszero(filledDenominator) { filledNumerator := numerator break } shr(OrderStatus_filledNumerator_offset, filledNumerator), MaxUint120 ) if eq(denominator, 1) { numerator := sub(filledDenominator, filledNumerator) denominator := filledDenominator filledNumerator := filledDenominator break } if eq(denominator, filledDenominator) { filledNumerator := add(numerator, filledNumerator) let carry := mul( sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) break } numerator := mul(numerator, filledDenominator) denominator := mul(denominator, filledDenominator) sub(filledNumerator, denominator), gt(filledNumerator, denominator) ) numerator := sub(numerator, carry) filledNumerator := sub(filledNumerator, carry) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { function gcd(_a, _b) -> out { for { let _c := _b _b := mod(_a, _c) _a := _c } out := _a } let scaleDown := gcd( numerator, gcd(filledNumerator, denominator) ) filledNumerator := div(filledNumerator, safeScaleDown) denominator := div(denominator, safeScaleDown) gt(filledNumerator, MaxUint120), gt(denominator, MaxUint120) ) { mstore(0, Panic_error_selector) mstore(Panic_error_code_ptr, Panic_arithmetic) revert(Error_selector_offset, Panic_error_length) } } break } orderStatusSlot, or( OrderStatus_ValidatedAndNotCancelled, or( shl( OrderStatus_filledNumerator_offset, filledNumerator ), shl(OrderStatus_filledDenominator_offset, denominator) ) ) ) } } sstore( function _compareItems( MemoryPointer originalItem, MemoryPointer newItem ) internal pure returns (uint256 isInvalid) { assembly { let itemType := mload(originalItem) let identifier := mload(add(originalItem, Common_identifier_offset)) if and(gt(itemType, 3), iszero(identifier)) { itemType := sub(3, eq(itemType, 4)) identifier := mload(add(newItem, Common_identifier_offset)) } let originalAmount := mload(add(originalItem, Common_amount_offset)) let newAmount := mload(add(newItem, Common_amount_offset)) isInvalid := iszero( and( eq( mload(add(originalItem, Common_token_offset)), mload(add(newItem, Common_token_offset)) ), eq(itemType, mload(newItem)) ), eq( identifier, mload(add(newItem, Common_identifier_offset)) ), eq( originalAmount, mload(add(originalItem, Common_endAmount_offset)) ) ) ) ) } } function _compareItems( MemoryPointer originalItem, MemoryPointer newItem ) internal pure returns (uint256 isInvalid) { assembly { let itemType := mload(originalItem) let identifier := mload(add(originalItem, Common_identifier_offset)) if and(gt(itemType, 3), iszero(identifier)) { itemType := sub(3, eq(itemType, 4)) identifier := mload(add(newItem, Common_identifier_offset)) } let originalAmount := mload(add(originalItem, Common_amount_offset)) let newAmount := mload(add(newItem, Common_amount_offset)) isInvalid := iszero( and( eq( mload(add(originalItem, Common_token_offset)), mload(add(newItem, Common_token_offset)) ), eq(itemType, mload(newItem)) ), eq( identifier, mload(add(newItem, Common_identifier_offset)) ), eq( originalAmount, mload(add(originalItem, Common_endAmount_offset)) ) ) ) ) } } function _compareItems( MemoryPointer originalItem, MemoryPointer newItem ) internal pure returns (uint256 isInvalid) { assembly { let itemType := mload(originalItem) let identifier := mload(add(originalItem, Common_identifier_offset)) if and(gt(itemType, 3), iszero(identifier)) { itemType := sub(3, eq(itemType, 4)) identifier := mload(add(newItem, Common_identifier_offset)) } let originalAmount := mload(add(originalItem, Common_amount_offset)) let newAmount := mload(add(newItem, Common_amount_offset)) isInvalid := iszero( and( eq( mload(add(originalItem, Common_token_offset)), mload(add(newItem, Common_token_offset)) ), eq(itemType, mload(newItem)) ), eq( identifier, mload(add(newItem, Common_identifier_offset)) ), eq( originalAmount, mload(add(originalItem, Common_endAmount_offset)) ) ) ) ) } } and( and( function _checkRecipients( address originalRecipient, address newRecipient ) internal pure returns (uint256 isInvalid) { assembly { isInvalid := iszero( or( iszero(originalRecipient), eq(newRecipient, originalRecipient) ) ) } } function _checkRecipients( address originalRecipient, address newRecipient ) internal pure returns (uint256 isInvalid) { assembly { isInvalid := iszero( or( iszero(originalRecipient), eq(newRecipient, originalRecipient) ) ) } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } ( function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } orderParameters.offer = offer; function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } orderParameters.consideration = consideration; function _getGeneratedOrder( OrderParameters memory orderParameters, bytes memory context, bool revertOnInvalid ) internal returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } { address offerer = orderParameters.offerer; bool success; (MemoryPointer cdPtr, uint256 size) = _encodeGenerateOrder( orderParameters, context ); assembly { success := call(gas(), offerer, 0, cdPtr, size, 0, 0) } { uint256 contractNonce; unchecked { contractNonce = _contractNonces[offerer]++; } assembly { orderHash := xor( contractNonce, shl(ContractOrder_orderHash_offerer_shift, offerer) ) } } if (!success) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } uint256 errorBuffer, OfferItem[] memory offer, ConsiderationItem[] memory consideration ) = _convertGetGeneratedOrderResult(_decodeGenerateOrderReturndata)(); if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } { uint256 originalOfferLength = orderParameters.offer.length; uint256 newOfferLength = offer.length; if (originalOfferLength > newOfferLength) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < originalOfferLength; ) { MemoryPointer mPtrOriginal = orderParameters .offer[i] .toMemoryPointer(); MemoryPointer mPtrNew = offer[i].toMemoryPointer(); errorBuffer |= _cast( mPtrOriginal .offset(Common_amount_offset) .readUint256() > mPtrNew.offset(Common_amount_offset).readUint256() ) | _compareItems(mPtrOriginal, mPtrNew); unchecked { ++i; } } } { ConsiderationItem[] memory originalConsiderationArray = ( orderParameters.consideration ); uint256 newConsiderationLength = consideration.length; if (newConsiderationLength > originalConsiderationArray.length) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } for (uint256 i = 0; i < newConsiderationLength; ) { MemoryPointer mPtrOriginal = originalConsiderationArray[i] .toMemoryPointer(); MemoryPointer mPtrNew = consideration[i].toMemoryPointer(); errorBuffer |= _cast( mPtrNew.offset(Common_amount_offset).readUint256() > mPtrOriginal .offset(Common_amount_offset) .readUint256() ) | _compareItems(mPtrOriginal, mPtrNew) | _checkRecipients( mPtrOriginal .offset(ConsiderItem_recipient_offset) .readAddress(), mPtrNew .offset(ConsiderItem_recipient_offset) .readAddress() ); unchecked { ++i; } } } if (errorBuffer != 0) { return _revertOrReturnEmpty(revertOnInvalid, orderHash); } } return (orderHash, 1, 1); function _cancel( OrderComponents[] calldata orders ) internal returns (bool cancelled) { _assertNonReentrant(); OrderStatus storage orderStatus; bool anyInvalidCallerOrContractOrder; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ) { OrderComponents calldata order = orders[i]; address offerer = order.offerer; address zone = order.zone; OrderType orderType = order.orderType; assembly { anyInvalidCallerOrContractOrder := or( anyInvalidCallerOrContractOrder, or( eq(orderType, 4), iszero( or(eq(caller(), offerer), eq(caller(), zone)) ) ) ) } bytes32 orderHash = _deriveOrderHash( _toOrderParametersReturnType( _decodeOrderComponentsAsOrderParameters )(order.toCalldataPointer()), order.counter ); orderStatus.isCancelled = true; } } if (anyInvalidCallerOrContractOrder) { _revertCannotCancelOrder(); } } function _cancel( OrderComponents[] calldata orders ) internal returns (bool cancelled) { _assertNonReentrant(); OrderStatus storage orderStatus; bool anyInvalidCallerOrContractOrder; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ) { OrderComponents calldata order = orders[i]; address offerer = order.offerer; address zone = order.zone; OrderType orderType = order.orderType; assembly { anyInvalidCallerOrContractOrder := or( anyInvalidCallerOrContractOrder, or( eq(orderType, 4), iszero( or(eq(caller(), offerer), eq(caller(), zone)) ) ) ) } bytes32 orderHash = _deriveOrderHash( _toOrderParametersReturnType( _decodeOrderComponentsAsOrderParameters )(order.toCalldataPointer()), order.counter ); orderStatus.isCancelled = true; } } if (anyInvalidCallerOrContractOrder) { _revertCannotCancelOrder(); } } function _cancel( OrderComponents[] calldata orders ) internal returns (bool cancelled) { _assertNonReentrant(); OrderStatus storage orderStatus; bool anyInvalidCallerOrContractOrder; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ) { OrderComponents calldata order = orders[i]; address offerer = order.offerer; address zone = order.zone; OrderType orderType = order.orderType; assembly { anyInvalidCallerOrContractOrder := or( anyInvalidCallerOrContractOrder, or( eq(orderType, 4), iszero( or(eq(caller(), offerer), eq(caller(), zone)) ) ) ) } bytes32 orderHash = _deriveOrderHash( _toOrderParametersReturnType( _decodeOrderComponentsAsOrderParameters )(order.toCalldataPointer()), order.counter ); orderStatus.isCancelled = true; } } if (anyInvalidCallerOrContractOrder) { _revertCannotCancelOrder(); } } function _cancel( OrderComponents[] calldata orders ) internal returns (bool cancelled) { _assertNonReentrant(); OrderStatus storage orderStatus; bool anyInvalidCallerOrContractOrder; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ) { OrderComponents calldata order = orders[i]; address offerer = order.offerer; address zone = order.zone; OrderType orderType = order.orderType; assembly { anyInvalidCallerOrContractOrder := or( anyInvalidCallerOrContractOrder, or( eq(orderType, 4), iszero( or(eq(caller(), offerer), eq(caller(), zone)) ) ) ) } bytes32 orderHash = _deriveOrderHash( _toOrderParametersReturnType( _decodeOrderComponentsAsOrderParameters )(order.toCalldataPointer()), order.counter ); orderStatus.isCancelled = true; } } if (anyInvalidCallerOrContractOrder) { _revertCannotCancelOrder(); } } orderStatus = _orderStatus[orderHash]; orderStatus.isValidated = false; emit OrderCancelled(orderHash, offerer, zone); ++i; function _cancel( OrderComponents[] calldata orders ) internal returns (bool cancelled) { _assertNonReentrant(); OrderStatus storage orderStatus; bool anyInvalidCallerOrContractOrder; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ) { OrderComponents calldata order = orders[i]; address offerer = order.offerer; address zone = order.zone; OrderType orderType = order.orderType; assembly { anyInvalidCallerOrContractOrder := or( anyInvalidCallerOrContractOrder, or( eq(orderType, 4), iszero( or(eq(caller(), offerer), eq(caller(), zone)) ) ) ) } bytes32 orderHash = _deriveOrderHash( _toOrderParametersReturnType( _decodeOrderComponentsAsOrderParameters )(order.toCalldataPointer()), order.counter ); orderStatus.isCancelled = true; } } if (anyInvalidCallerOrContractOrder) { _revertCannotCancelOrder(); } } cancelled = true; function _validate( Order[] memory orders ) internal returns (bool validated) { _assertNonReentrant(); OrderStatus storage orderStatus; bytes32 orderHash; address offerer; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ++i) { Order memory order = orders[i]; OrderParameters memory orderParameters = order.parameters; if (orderParameters.orderType == OrderType.CONTRACT) { continue; } orderParameters ); orderHash, orderStatus, ); if (!orderStatus.isValidated) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } } } } } function _validate( Order[] memory orders ) internal returns (bool validated) { _assertNonReentrant(); OrderStatus storage orderStatus; bytes32 orderHash; address offerer; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ++i) { Order memory order = orders[i]; OrderParameters memory orderParameters = order.parameters; if (orderParameters.orderType == OrderType.CONTRACT) { continue; } orderParameters ); orderHash, orderStatus, ); if (!orderStatus.isValidated) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } } } } } function _validate( Order[] memory orders ) internal returns (bool validated) { _assertNonReentrant(); OrderStatus storage orderStatus; bytes32 orderHash; address offerer; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ++i) { Order memory order = orders[i]; OrderParameters memory orderParameters = order.parameters; if (orderParameters.orderType == OrderType.CONTRACT) { continue; } orderParameters ); orderHash, orderStatus, ); if (!orderStatus.isValidated) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } } } } } function _validate( Order[] memory orders ) internal returns (bool validated) { _assertNonReentrant(); OrderStatus storage orderStatus; bytes32 orderHash; address offerer; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ++i) { Order memory order = orders[i]; OrderParameters memory orderParameters = order.parameters; if (orderParameters.orderType == OrderType.CONTRACT) { continue; } orderParameters ); orderHash, orderStatus, ); if (!orderStatus.isValidated) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } } } } } offerer = orderParameters.offerer; orderHash = _assertConsiderationLengthAndGetOrderHash( orderStatus = _orderStatus[orderHash]; _verifyOrderStatus( function _validate( Order[] memory orders ) internal returns (bool validated) { _assertNonReentrant(); OrderStatus storage orderStatus; bytes32 orderHash; address offerer; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ++i) { Order memory order = orders[i]; OrderParameters memory orderParameters = order.parameters; if (orderParameters.orderType == OrderType.CONTRACT) { continue; } orderParameters ); orderHash, orderStatus, ); if (!orderStatus.isValidated) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } } } } } function _validate( Order[] memory orders ) internal returns (bool validated) { _assertNonReentrant(); OrderStatus storage orderStatus; bytes32 orderHash; address offerer; unchecked { uint256 totalOrders = orders.length; for (uint256 i = 0; i < totalOrders; ++i) { Order memory order = orders[i]; OrderParameters memory orderParameters = order.parameters; if (orderParameters.orderType == OrderType.CONTRACT) { continue; } orderParameters ); orderHash, orderStatus, ); if (!orderStatus.isValidated) { if ( orderParameters.consideration.length != orderParameters.totalOriginalConsiderationItems ) { _revertConsiderationLengthNotEqualToTotalOriginal(); } } } } } _verifySignature(offerer, orderHash, order.signature); orderStatus.isValidated = true; emit OrderValidated(orderHash, orderParameters); validated = true; function _getOrderStatus( bytes32 orderHash ) internal view returns ( bool isValidated, bool isCancelled, uint256 totalFilled, uint256 totalSize ) { OrderStatus storage orderStatus = _orderStatus[orderHash]; return ( orderStatus.isValidated, orderStatus.isCancelled, orderStatus.numerator, orderStatus.denominator ); } function _revertOrReturnEmpty( bool revertOnInvalid, bytes32 contractOrderHash ) internal pure returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if (revertOnInvalid) { _revertInvalidContractOrder(contractOrderHash); } return (contractOrderHash, 0, 0); } function _revertOrReturnEmpty( bool revertOnInvalid, bytes32 contractOrderHash ) internal pure returns (bytes32 orderHash, uint256 numerator, uint256 denominator) { if (revertOnInvalid) { _revertInvalidContractOrder(contractOrderHash); } return (contractOrderHash, 0, 0); } function _doesNotSupportPartialFills( OrderType orderType, uint256 numerator, uint256 denominator ) internal pure returns (bool isFullOrder) { assembly { isFullOrder := and( lt(numerator, denominator), iszero(and(orderType, 1)) ) } } function _doesNotSupportPartialFills( OrderType orderType, uint256 numerator, uint256 denominator ) internal pure returns (bool isFullOrder) { assembly { isFullOrder := and( lt(numerator, denominator), iszero(and(orderType, 1)) ) } } }
4,301,527
[ 1, 2448, 5126, 225, 374, 410, 225, 4347, 5126, 1914, 14176, 3746, 358, 18075, 11077, 540, 471, 9702, 3675, 1267, 18, 19, 11065, 1267, 434, 1517, 1353, 261, 877, 690, 16, 13927, 16, 471, 8330, 6300, 2934, 11065, 1661, 764, 364, 6835, 10067, 414, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4347, 5126, 353, 13146, 16, 10912, 17419, 288, 203, 565, 2874, 12, 3890, 1578, 516, 4347, 1482, 13, 3238, 389, 1019, 1482, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 389, 16351, 3989, 764, 31, 203, 203, 203, 565, 445, 389, 5662, 8252, 2448, 1876, 1891, 1482, 12, 203, 3639, 1731, 1578, 1353, 2310, 16, 203, 3639, 1731, 745, 892, 3372, 203, 565, 3885, 12, 2867, 356, 2544, 305, 2933, 13, 13146, 12, 591, 2544, 305, 2933, 13, 2618, 203, 565, 262, 2713, 288, 203, 3639, 1758, 10067, 264, 31, 203, 3639, 19931, 288, 203, 5411, 10067, 264, 519, 745, 72, 3145, 6189, 12, 8252, 2448, 67, 792, 18459, 67, 4315, 5263, 13, 203, 3639, 289, 203, 203, 203, 5411, 1353, 2310, 16, 203, 5411, 1353, 1482, 16, 203, 3639, 11272, 203, 203, 3639, 309, 16051, 1019, 1482, 18, 291, 24258, 13, 288, 203, 5411, 389, 8705, 5374, 12, 792, 18459, 16, 1353, 2310, 16, 3372, 1769, 203, 3639, 289, 203, 203, 3639, 1353, 1482, 18, 291, 21890, 273, 629, 31, 203, 3639, 1353, 1482, 18, 2107, 7385, 273, 404, 31, 203, 3639, 1353, 1482, 18, 13002, 26721, 273, 404, 31, 203, 565, 289, 203, 203, 565, 262, 2713, 288, 203, 3639, 1758, 10067, 264, 31, 203, 3639, 19931, 288, 203, 5411, 10067, 264, 519, 745, 72, 3145, 6189, 12, 8252, 2448, 67, 792, 18459, 67, 4315, 5263, 13, 203, 3639, 289, 203, 203, 203, 5411, 1353, 2310, 16, 203, 5411, 1353, 1482, 16, 203, 3639, 11272, 203, 203, 2 ]
pragma solidity ^0.4.16; // ---------------------------------------------------------------------------- // contract WhiteListAccess // ---------------------------------------------------------------------------- contract WhiteListAccess { function WhiteListAccess() public { owner = msg.sender; whitelist[owner] = true; whitelist[address(this)] = true; } address public owner; mapping (address => bool) whitelist; modifier onlyOwner {require(msg.sender == owner); _;} modifier onlyWhitelisted {require(whitelist[msg.sender]); _;} function addToWhiteList(address trusted) public onlyOwner() { whitelist[trusted] = true; } function removeFromWhiteList(address untrusted) public onlyOwner() { whitelist[untrusted] = false; } } // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // CNT_Common contract // ---------------------------------------------------------------------------- contract CNT_Common is WhiteListAccess { string public name; function CNT_Common() public { } // Deployment address public SALE_address; // CNT_Crowdsale } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract Token is ERC20Interface, CNT_Common { using SafeMath for uint; bool public freezed; bool public initialized; uint8 public decimals; uint public totSupply; string public symbol; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Token(uint8 _decimals, uint _millions, string _name, string _sym) public { owner = msg.sender; symbol = _sym; name = _name; decimals = _decimals; totSupply = _millions * 10**6 * 10**uint(decimals); balances[owner] = totSupply; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totSupply - balances[SALE_address]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!freezed); require(initialized); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function desapprove(address spender) public returns (bool success) { allowed[msg.sender][spender] = 0; return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(!freezed); require(initialized); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // function init(address _sale) public { require(!initialized); // we need to know the CNTTokenSale and NewRichOnTheBlock Contract address before distribute to them SALE_address = _sale; balances[SALE_address] = totSupply; balances[address(this)] = 0; balances[owner] = 0; whitelist[SALE_address] = true; initialized = true; freezed = true; } function ico_distribution(address to, uint tokens) public onlyWhitelisted() { require(initialized); balances[SALE_address] = balances[SALE_address].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(SALE_address, to, tokens); } function balanceOfMine() public returns (uint) { return balances[msg.sender]; } function rename(string _name) public onlyOwner() { name = _name; } function unfreeze() public onlyOwner() { freezed = false; } function refreeze() public onlyOwner() { freezed = true; } } contract CNT_Token is Token(18, 300, "Chip", "CNT") { function CNT_Token() public {} } contract BGB_Token is Token(18, 300, "BG-Coin", "BGB") { function BGB_Token() public {} } contract VPE_Token is Token(18, 100, "Vapaee", "VPE") { function VPE_Token() public {} } contract GVPE_Token is Token(18, 1, "Golden Vapaee", "GVPE") { function GVPE_Token() public {} } contract EOS is Token(18, 1000, "EOS Dummie", "EOS") { function EOS() public {} }
------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(!freezed); require(initialized); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; }
465,992
[ 1, 29461, 12279, 1375, 7860, 68, 628, 326, 1375, 2080, 68, 2236, 358, 326, 1375, 869, 68, 2236, 1021, 4440, 2236, 1297, 1818, 1240, 18662, 2430, 6617, 537, 5825, 24950, 72, 364, 272, 9561, 628, 326, 1375, 2080, 68, 2236, 471, 300, 6338, 2236, 1297, 1240, 18662, 11013, 358, 7412, 300, 348, 1302, 264, 1297, 1240, 18662, 1699, 1359, 358, 7412, 300, 374, 460, 29375, 854, 2935, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 5, 9156, 94, 329, 1769, 203, 3639, 2583, 12, 13227, 1769, 203, 3639, 324, 26488, 63, 2080, 65, 273, 324, 26488, 63, 2080, 8009, 1717, 12, 7860, 1769, 203, 3639, 2935, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 2080, 6362, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 203, 3639, 12279, 12, 2080, 16, 358, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]