file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/contracts/bridge/Wallets.sol
Gets BTC balance for given the wallet. walletPubKeyHash 20-byte public key hash of the wallet. walletMainUtxo Data of the wallet's main UTXO, as currently known on the Ethereum chain. return walletBtcBalance Current BTC balance for the given wallet. Requirements: - `walletMainUtxo` components must point to the recent main UTXO of the given wallet, as currently known on the Ethereum chain. If the wallet has no main UTXO, this parameter can be empty as it is ignored. If the wallet has a main UTXO hash set, cross-check it with the provided plain-text parameter and get the transaction output value as BTC balance. Otherwise, the BTC balance is just zero.
function getWalletBtcBalance( BridgeState.Storage storage self, bytes20 walletPubKeyHash, BitcoinTx.UTXO calldata walletMainUtxo ) internal view returns (uint64 walletBtcBalance) { bytes32 walletMainUtxoHash = self .registeredWallets[walletPubKeyHash] .mainUtxoHash; if (walletMainUtxoHash != bytes32(0)) { require( keccak256( abi.encodePacked( walletMainUtxo.txHash, walletMainUtxo.txOutputIndex, walletMainUtxo.txOutputValue ) ) == walletMainUtxoHash, "Invalid wallet main UTXO data" ); walletBtcBalance = walletMainUtxo.txOutputValue; } return walletBtcBalance; }
4,856,627
pragma solidity ^0.4.23; /* * Contract that is working with ERC223 tokens * https://github.com/ethereum/EIPs/issues/223 */ /// @title ERC223ReceivingContract - Standard contract implementation for compatibility with ERC223 tokens. contract ERC223ReceivingContract { /// @dev Function that is called when a user or another contract wants to transfer funds. /// @param _from Transaction initiator, analogue of msg.sender /// @param _value Number of tokens to transfer. /// @param _data Data containig a function signature and/or parameters function tokenFallback(address _from, uint256 _value, bytes _data) public; } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { assert(b != 0); return a % b; } } /// @title Base Token contract contract Token { /* * Implements ERC 20 standard. * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md * https://github.com/ethereum/EIPs/issues/20 * * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 */ uint256 public totalSupply; /* * ERC 20 */ function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); /* * ERC 223 */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool success); /* * Events */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /// @title Standard token contract - Standard token implementation. contract StandardToken is Token { /* * Data structures */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != 0x0); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* * Read functions */ /// @dev Returns number of allowed tokens that a spender can transfer on /// behalf of a token owner. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by the given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /// @title Vitalik2X Token contract Vitalik2XToken is StandardToken { using SafeMath for uint256; /* * Token metadata */ string constant public symbol = "V2X"; string constant public name = "Vitalik2X"; uint256 constant public decimals = 18; uint256 constant public multiplier = 10 ** decimals; address public owner; uint256 public creationBlock; uint256 public mainPotTokenBalance; uint256 public mainPotETHBalance; mapping (address => uint256) blockLock; event Mint(address indexed to, uint256 amount); event DonatedTokens(address indexed donator, uint256 amount); event DonatedETH(address indexed donator, uint256 amount); event SoldTokensFromPot(address indexed seller, uint256 amount); event BoughtTokensFromPot(address indexed buyer, uint256 amount); /* * Public functions */ /// @dev Function create the token and distribute to the deploying address constructor() public { owner = msg.sender; totalSupply = 10 ** decimals; balances[msg.sender] = totalSupply; creationBlock = block.number; emit Transfer(0x0, msg.sender, totalSupply); } modifier onlyOwner() { require(msg.sender == owner); _; } /* * External Functions */ /// @dev Adds the tokens to the main Pot. function donateTokensToMainPot(uint256 amount) external returns (bool){ require(_transfer(this, amount)); mainPotTokenBalance = mainPotTokenBalance.add(amount); emit DonatedTokens(msg.sender, amount); return true; } function donateETHToMainPot() external payable returns (bool){ require(msg.value > 0); mainPotETHBalance = mainPotETHBalance.add(msg.value); emit DonatedETH(msg.sender, msg.value); return true; } /// @dev Automatically sends a proportional percent of the ETH balance from the pot for proportion of the Tokens deposited. function sellTokensToPot(uint256 amount) external returns (bool) { uint256 amountBeingPaid = ethSliceAmount(amount); require(amountBeingPaid <= ethSliceCap(), "Token amount sent is above the cap."); require(_transfer(this, amount)); mainPotTokenBalance = mainPotTokenBalance.add(amount); mainPotETHBalance = mainPotETHBalance.sub(amountBeingPaid); msg.sender.transfer(amountBeingPaid); emit SoldTokensFromPot(msg.sender, amount); return true; } /// @dev Automatically sends a proportional percent of the VTK2X token balance from the pot for proportion of the ETH deposited. function buyTokensFromPot() external payable returns (uint256) { require(msg.value > 0); uint256 amountBuying = tokenSliceAmount(msg.value); require(amountBuying <= tokenSliceCap(), "Msg.value is above the cap."); require(mainPotTokenBalance >= 1 finney, "Pot does not have enough tokens."); mainPotETHBalance = mainPotETHBalance.add(msg.value); mainPotTokenBalance = mainPotTokenBalance.sub(amountBuying); balances[address(this)] = balances[address(this)].sub(amountBuying); balances[msg.sender] = balances[msg.sender].add(amountBuying); emit Transfer(address(this), msg.sender, amountBuying); emit BoughtTokensFromPot(msg.sender, amountBuying); return amountBuying; } /// @dev Returns the block number the given address is locked until. /// @param _owner Address of token owner. /// @return Returns block number the lock is released. function blockLockOf(address _owner) external view returns (uint256) { return blockLock[_owner]; } /// @dev external function to retrieve ETH sent to the contract. function withdrawETH() external onlyOwner { owner.transfer(address(this).balance.sub(mainPotETHBalance)); } /// @dev external function to retrieve tokens accidentally sent to the contract. function withdrawToken(address token) external onlyOwner { require(token != address(this)); Token erc20 = Token(token); erc20.transfer(owner, erc20.balanceOf(this)); } /* * Public Functions */ /// @dev public function to retrieve the ETH amount. function ethSliceAmount(uint256 amountOfTokens) public view returns (uint256) { uint256 amountBuying = mainPotETHBalance.mul(amountOfTokens).div(mainPotTokenBalance); amountBuying = amountBuying.sub(amountBuying.mul(amountOfTokens).div(mainPotTokenBalance)); return amountBuying; } /// @dev public function to retrieve the max ETH slice allotted. function ethSliceCap() public view returns (uint256) { return mainPotETHBalance.mul(30).div(100); } /// @dev public function to retrieve the percentage of ETH user wants from pot. function ethSlicePercentage(uint256 amountOfTokens) public view returns (uint256) { uint256 amountOfTokenRecieved = ethSliceAmount(amountOfTokens); return amountOfTokenRecieved.mul(100).div(mainPotETHBalance); } /// @dev public function to retrieve the current pot reward amount. function tokenSliceAmount(uint256 amountOfETH) public view returns (uint256) { uint256 amountBuying = mainPotTokenBalance.mul(amountOfETH).div(mainPotETHBalance); amountBuying = amountBuying.sub(amountBuying.mul(amountOfETH).div(mainPotETHBalance)); return amountBuying; } /// @dev public function to retrieve the max token slice allotted. function tokenSliceCap() public view returns (uint256) { return mainPotTokenBalance.mul(30).div(100); } /// @dev public function to retrieve the percentage of ETH user wants from pot. function tokenSlicePercentage(uint256 amountOfEth) public view returns (uint256) { uint256 amountOfEthRecieved = tokenSliceAmount(amountOfEth); return amountOfEthRecieved.mul(100).div(mainPotTokenBalance); } /// @dev public function to check the status of account's lock. function accountLocked() public view returns (bool) { return (block.number < blockLock[msg.sender]); } function transfer(address _to, uint256 _value) public returns (bool) { require(block.number >= blockLock[msg.sender], "Address is still locked."); if (_to == address(this)) { return _vitalikize(msg.sender, _value); } else { return _transfer(_to, _value); } } /// @notice Send `_value` tokens to `_to` from `msg.sender` and trigger /// tokenFallback if sender is a contract. /// @dev Function that is called when a user or another contract wants to transfer funds. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. /// @param _data Data to be sent to tokenFallback /// @return Returns success of function call. function transfer( address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); // Transfers tokens normally as per ERC20 standards require(transfer(_to, _value)); uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } // If codeLength is > 0, it means it is a contract, handle fallback if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } return true; } /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed. /// @dev Allows for an approved third party to transfer tokens from one /// address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(block.number >= blockLock[_from], "Address is still locked."); require(_from != 0x0); require(_to != 0x0); require(_to != address(this)); // Balance of sender is legit balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /* * Internal functions */ /// @notice Send `_value` tokens to `_to` from `msg.sender`. /// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function _transfer(address _to, uint256 _value) internal returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /// @dev Mints the amount of token passed and sends it to the sender function _vitalikize(address _sender, uint256 _value) internal returns (bool) { require(balances[_sender] >= _value, "Owner doesnt have enough tokens."); uint256 calcBlockLock = (block.number - creationBlock)/5; blockLock[_sender] = block.number + (calcBlockLock > 2600 ? calcBlockLock : 2600); require(mint(_sender, _value), "Minting failed"); emit Transfer(address(0), _sender, _value); return true; } function mint(address _address, uint256 _amount) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_address] = balances[_address].add(_amount); return true; } }
Internal functions/ Send `_value` tokens to `_to` from `msg.sender`. Transfers sender's tokens to a given address. Returns success. _to Address of token receiver. _value Number of tokens to transfer. return Returns success of function call.
function _transfer(address _to, uint256 _value) internal returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
12,921,315
./full_match/42161/0xd18C6a3488d424920dD9f6A4187645794df96383/sources/src/Facets/OFTWrapperFacet.sol
Initialize local variables for the OFTWrapper Facet. chainIdConfigs Chain Id configuration data.
function initOFTWrapper(ChainIdConfig[] calldata chainIdConfigs) external { LibDiamond.enforceIsContractOwner(); Storage storage sm = getStorage(); if (sm.initialized) { revert AlreadyInitialized(); } for (uint256 i = 0; i < chainIdConfigs.length; i++) { sm.layerZeroChainId[chainIdConfigs[i].chainId] = chainIdConfigs[i] .layerZeroChainId; } sm.initialized = true; emit OFTWrapperInitialized(chainIdConfigs); }
16,302,321
// Copyright 2019-2020 The Energi Core Authors // This file is part of Energi Core. // // Energi Core 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. // // Energi Core 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 Energi Core. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.5.16; import { IGovernedProxy, IGovernedContract, IBlockReward, StorageMasternodeRegistryV1, MasternodeRegistryV2 } from "./MasternodeRegistryV2.sol"; /// @notice MasternodeRegistryV2_2 is a mostly trivial update to MasternodeRegistryV2 /// @dev MasternodeRegistryV2_2 disables the proof of service invalidations due to a chain-split vulnerability contract MasternodeRegistryV2_2 is MasternodeRegistryV2 { bool migration_complete; uint inactive_count; /// @notice construct a new MasternodeRegistryV2_2 /// @param _proxy The MasternodeRegistry proxy address /// @param _token_proxy The Masternode Token (MNRG) proxy address /// @param _treasury_proxy The Treasury proxy address /// @param _config MasternodeRegistry configuration ( MNRequireValidation, MNValidationPeriod, MNCleanupPeriod, MNEverCollateral, MNRewardsPerBlock ) constructor( address _proxy, IGovernedProxy _token_proxy, IGovernedProxy _treasury_proxy, uint[5] memory _config ) public MasternodeRegistryV2(_proxy, _token_proxy, _treasury_proxy, _config) { migration_complete = false; inactive_count = 0; current_masternode = address(0); current_payouts = 0; } /// @notice proof of service invalidation /// @dev this is disabled due to chain split vulnerability in previous versions /// @dev masternode address is the masternode to invalidate. function invalidate(address /*masternode*/) external noReentry { require(false, "invalidations disabled"); } /// @notice this migration function triggered by governance upgrade when replacing another version /// @dev see migrateStatusPartial() - masternode status must be migrated before governance upgrade! /// @param _oldImpl the previous masternode registry being migrated function _migrate(IGovernedContract _oldImpl) internal { require(migration_complete, "cannot upgrade before migration"); // Dispose v1storage.kill(); MasternodeRegistryV2 oldinstance = MasternodeRegistryV2(address(_oldImpl)); v1storage = oldinstance.v1storage(); // Migration data mn_announced = oldinstance.mn_announced(); if (current_masternode == oldinstance.current_masternode()) { current_payouts = oldinstance.current_payouts(); } // Other data mn_ever_collateral = oldinstance.mn_ever_collateral(); mn_active_collateral = oldinstance.mn_active_collateral(); mn_announced_collateral = oldinstance.mn_announced_collateral(); last_block_number = block.number; } /// @notice migrate masternode statuses from the current masternode registry /// @dev We migrate the available masternodes till gas left is less than or equal to 10000, /// @dev so this function will use the gas limit to determine how many masternodes /// @dev that will be migrated at a ago. function migrateStatusPartial() external noReentry { require(!migration_complete, "migration already done"); // address(uint160()) cast converts from non-payable address to allow cast to IGovernedProxy() IGovernedContract current_mnreg_impl = IGovernedProxy(address(uint160(proxy))).impl(); require(address(current_mnreg_impl) != address(this), "cannot migrate from self"); MasternodeRegistryV2 old_registry = MasternodeRegistryV2(address(current_mnreg_impl)); mn_active = old_registry.mn_active(); uint currentlength = validator_list.length + inactive_count; require(currentlength < mn_active, "migration already complete"); for (uint i = currentlength; i < mn_active; ++i) { // limit chunk of MN migrated using gas left if (gasleft() <= 500000) break; address mn = old_registry.validator_list(i); // skip inactive masternodes if (!old_registry.isActive(mn) || old_registry.canHeartbeat(mn)) { inactive_count++; continue; } else if (current_masternode == address(0)) { current_masternode = mn; } Status memory status; ( status.sw_features, status.next_heartbeat, status.inactive_since, , // status.validator_index is reset when adding to the list , // status.invalidations not copied (not relevant to mn registry v2.2) status.seq_payouts, // status.last_vote_epoch not copied (not relevant to mn registry v2.2) ) = old_registry.mn_status(mn); status.validator_index = validator_list.length; validator_list.push(mn); mn_status[mn] = status; } if (validator_list.length >= (mn_active - inactive_count)) { mn_active = validator_list.length; migration_complete = true; } } /// @notice this function triggered by governance upgrade when this contract is replaced by a newer version /// @dev see migrateStatusPartial() - masternode status must be migrated before governance upgrade! /// @param _newImpl the new masternode registry that is replacing this one function _destroy(IGovernedContract _newImpl) internal { v1storage.setOwner(_newImpl); } /// @notice the reward() function from IBlockReward is called as part of the block reward loop to pay the masternode function reward() external payable noReentry { // NOTE: ensure to move of remaining from the previous times to Treasury //--- uint diff = address(this).balance - msg.value; if (int(diff) > 0) { IBlockReward treasury = IBlockReward(address(treasury_proxy.impl())); treasury.reward.value(diff)(); } //--- // SECURITY: do processing only when reward is exactly as expected if (msg.value == REWARD_MASTERNODE_V1) { // SECURITY: this check is essential against Masternode skip attacks! require(last_block_number < block.number, "Call outside of governance!"); last_block_number = block.number; // Safety checks assert(msg.value == address(this).balance); uint fractions = payments_per_block; for (uint i = fractions; i > 0; --i) { assert(gasleft() > GAS_RESERVE); // solium-disable-next-line no-empty-blocks while ((gasleft() > GAS_RESERVE) && !_reward()) {} } } } /// @notice For each payment in a block (payments_per_block) this function is called to pay the next eligible masternode function _reward() internal returns(bool) { // skip when there's no masternodes if (current_masternode == address(0)) { return true; } // get the status of the current masternode StorageMasternodeRegistryV1.Info memory mninfo = _mnInfo(v1storage, current_masternode); // move on to the next masternode if we are done paying if (current_payouts >= mn_status[current_masternode].seq_payouts) { current_masternode = mninfo.next; current_payouts = 0; mninfo = _mnInfo(v1storage, current_masternode); } bool success = false; // pay valid masternodes ValidationStatus validation = _checkStatus(mn_status[current_masternode], mninfo); if (validation == ValidationStatus.MNActive) { uint reward_payment = REWARD_MASTERNODE_V1 / payments_per_block; // solium-disable-next-line security/no-send success = mninfo.owner.send(reward_payment); current_payouts++; // denounce invalid masternodes if they have a collateral issue or have been around too long // solium-disable-next-line security/no-block-members } else if ((validation == ValidationStatus.MNCollaterIssue) || ((block.timestamp - mn_status[current_masternode].inactive_since) > cleanup_period)) { _denounce(current_masternode, mninfo.owner); // deactivate invalid masternodes } else if (mn_status[current_masternode].seq_payouts > 0) { mn_status[current_masternode].seq_payouts = 0; // solium-disable-next-line security/no-block-members mn_status[current_masternode].inactive_since = block.timestamp; _deactive_common(current_masternode, mninfo.collateral); current_masternode = mninfo.next; current_payouts = 0; emit Deactivated(current_masternode); } return success; } /// @notice fallback function not allowed function () external payable { revert("Not supported"); } }
the reward() function from IBlockReward is called as part of the block reward loop to pay the masternode NOTE: ensure to move of remaining from the previous times to Treasury------ SECURITY: do processing only when reward is exactly as expected SECURITY: this check is essential against Masternode skip attacks! Safety checks solium-disable-next-line no-empty-blocks
function reward() external payable noReentry { uint diff = address(this).balance - msg.value; if (int(diff) > 0) { IBlockReward treasury = IBlockReward(address(treasury_proxy.impl())); treasury.reward.value(diff)(); } if (msg.value == REWARD_MASTERNODE_V1) { require(last_block_number < block.number, "Call outside of governance!"); last_block_number = block.number; assert(msg.value == address(this).balance); uint fractions = payments_per_block; for (uint i = fractions; i > 0; --i) { assert(gasleft() > GAS_RESERVE); } } }
2,477,717
./partial_match/1/0xd4bDCCa1CA76ceD6FC8BB1bA91C5D7c0Ca4fE567/sources/CToken.sol
Returns the current per-block supply interest rate for this cToken return The supply interest rate per block, scaled by 1e18/
function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves + totalFuseFees + totalAdminFees, reserveFactorMantissa + fuseFeeMantissa + adminFeeMantissa); }
3,684,725
/** *Submitted for verification at Etherscan.io on 2021-02-02 */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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/token/ERC20/IERC20.sol pragma solidity ^0.6.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: @bancor/token-governance/contracts/IClaimable.sol pragma solidity 0.6.12; /// @title Claimable contract interface interface IClaimable { function owner() external view returns (address); function transferOwnership(address newOwner) external; function acceptOwnership() external; } // File: @bancor/token-governance/contracts/IMintableToken.sol pragma solidity 0.6.12; /// @title Mintable Token interface interface IMintableToken is IERC20, IClaimable { function issue(address to, uint256 amount) external; function destroy(address from, uint256 amount) external; } // File: @bancor/token-governance/contracts/ITokenGovernance.sol pragma solidity 0.6.12; /// @title The interface for mintable/burnable token governance. interface ITokenGovernance { // The address of the mintable ERC20 token. function token() external view returns (IMintableToken); /// @dev Mints new tokens. /// /// @param to Account to receive the new amount. /// @param amount Amount to increase the supply by. /// function mint(address to, uint256 amount) external; /// @dev Burns tokens from the caller. /// /// @param amount Amount to decrease the supply by. /// function burn(uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ICheckpointStore.sol pragma solidity 0.6.12; /** * @dev Checkpoint store contract interface */ interface ICheckpointStore { function addCheckpoint(address _address) external; function addPastCheckpoint(address _address, uint256 _time) external; function addPastCheckpoints(address[] calldata _addresses, uint256[] calldata _times) external; function checkpoint(address _address) external view returns (uint256); } // File: solidity/contracts/utility/MathEx.sol pragma solidity 0.6.12; /** * @dev This library provides a set of complex math operations. */ library MathEx { /** * @dev returns the largest integer smaller than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the largest integer smaller than or equal to the square root of the positive integer */ function floorSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = _num / 2 + 1; uint256 y = (x + _num / x) / 2; while (x > y) { x = y; y = (x + _num / x) / 2; } return x; } /** * @dev returns the smallest integer larger than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the smallest integer larger than or equal to the square root of the positive integer */ function ceilSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = floorSqrt(_num); return x * x == _num ? x : x + 1; } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio( uint256 _n, uint256 _d, uint256 _max ) internal pure returns (uint256, uint256) { (uint256 n, uint256 d) = (_n, _d); if (n > _max || d > _max) { (n, d) = normalizedRatio(n, d, _max); } if (n != d) { return (n, d); } return (1, 1); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { if (_a <= _b) { return accurateRatio(_a, _b, _scale); } (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b". */ function accurateRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; // we can now safely compute `_a * _scale` _b /= c; } if (_a != _b) { uint256 n = _a * _scale; uint256 d = _a + _b; // can overflow if (d >= _a) { // no overflow in `_a + _b` uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x` uint256 y = _scale - x; return (x, y); } if (n < _b - (_b - _a) / 2) { return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b` } return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b` } return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + (_n % _d) / (_d - _d / 2); } /** * @dev returns the average number of decimal digits in a given list of positive integers * * @param _values list of positive integers * * @return the average number of decimal digits in the given list of positive integers */ function geometricMean(uint256[] memory _values) internal pure returns (uint256) { uint256 numOfDigits = 0; uint256 length = _values.length; for (uint256 i = 0; i < length; i++) { numOfDigits += decimalLength(_values[i]); } return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1); } /** * @dev returns the number of decimal digits in a given positive integer * * @param _x positive integer * * @return the number of decimal digits in the given positive integer */ function decimalLength(uint256 _x) internal pure returns (uint256) { uint256 y = 0; for (uint256 x = _x; x > 0; x /= 10) { y++; } return y; } /** * @dev returns the nearest integer to a given quotient * the computation is overflow-safe assuming that the input is sufficiently small * * @param _n quotient numerator * @param _d quotient denominator * * @return the nearest integer to the given quotient */ function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) { return (_n + _d / 2) / _d; } /** * @dev returns the larger of two values * * @param _val1 the first value * @param _val2 the second value */ function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) { return _val1 > _val2 ? _val1 : _val2; } } // File: solidity/contracts/utility/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @dev This contract provides protection against calling a function * (directly or indirectly) from within itself. */ contract ReentrancyGuard { uint256 private constant UNLOCKED = 1; uint256 private constant LOCKED = 2; // LOCKED while protected code is being executed, UNLOCKED otherwise uint256 private state = UNLOCKED; /** * @dev ensures instantiation only by sub-contracts */ constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); state = LOCKED; _; state = UNLOCKED; } // error message binary size optimization function _protected() internal view { require(state == UNLOCKED, "ERR_REENTRANCY"); } } // File: solidity/contracts/utility/interfaces/IOwned.sol pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev This contract provides support and utilities for contract ownership. */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public override { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/token/interfaces/IERC20Token.sol pragma solidity 0.6.12; /* ERC20 Standard Token interface */ interface IERC20Token { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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 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: solidity/contracts/utility/TokenHandler.sol pragma solidity 0.6.12; contract TokenHandler { bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)")); bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)")); /** * @dev executes the ERC20 token's `approve` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _spender approved address * @param _value allowance amount */ function safeApprove( IERC20Token _token, address _spender, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_APPROVE_FAILED"); } /** * @dev executes the ERC20 token's `transfer` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _to target address * @param _value transfer amount */ function safeTransfer( IERC20Token _token, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FAILED"); } /** * @dev executes the ERC20 token's `transferFrom` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _from source address * @param _to target address * @param _value transfer amount */ function safeTransferFrom( IERC20Token _token, address _from, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FROM_FAILED"); } } // File: solidity/contracts/utility/Types.sol pragma solidity 0.6.12; /** * @dev This contract provides types which can be used by various contracts. */ struct Fraction { uint256 n; // numerator uint256 d; // denominator } // File: solidity/contracts/utility/Time.sol pragma solidity 0.6.12; /* Time implementing contract */ contract Time { /** * @dev returns the current time */ function time() internal view virtual returns (uint256) { return block.timestamp; } } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address _address) { _validExternalAddress(_address); _; } // error message binary size optimization function _validExternalAddress(address _address) internal view { require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS"); } } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/token/interfaces/IDSToken.sol pragma solidity 0.6.12; /* DSToken interface */ interface IDSToken is IConverterAnchor, IERC20Token { function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStore.sol pragma solidity 0.6.12; /* Liquidity Protection Store interface */ interface ILiquidityProtectionStore is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function protectedLiquidity(uint256 _id) external view returns ( address, IDSToken, IERC20Token, uint256, uint256, uint256, uint256, uint256 ); function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, uint256 _reserveRateN, uint256 _reserveRateD, uint256 _timestamp ) external returns (uint256); function updateProtectedLiquidityAmounts( uint256 _id, uint256 _poolNewAmount, uint256 _reserveNewAmount ) external; function removeProtectedLiquidity(uint256 _id) external; function lockedBalance(address _provider, uint256 _index) external view returns (uint256, uint256); function lockedBalanceRange( address _provider, uint256 _startIndex, uint256 _endIndex ) external view returns (uint256[] memory, uint256[] memory); function addLockedBalance( address _provider, uint256 _reserveAmount, uint256 _expirationTime ) external returns (uint256); function removeLockedBalance(address _provider, uint256 _index) external; function systemBalance(IERC20Token _poolToken) external view returns (uint256); function incSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; function decSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStats.sol pragma solidity 0.6.12; /* Liquidity Protection Stats interface */ interface ILiquidityProtectionStats { function increaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function decreaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function addProviderPool(address provider, IDSToken poolToken) external returns (bool); function removeProviderPool(address provider, IDSToken poolToken) external returns (bool); function totalPoolAmount(IDSToken poolToken) external view returns (uint256); function totalReserveAmount(IDSToken poolToken, IERC20Token reserveToken) external view returns (uint256); function totalProviderAmount( address provider, IDSToken poolToken, IERC20Token reserveToken ) external view returns (uint256); function providerPools(address provider) external view returns (IDSToken[] memory); } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSettings.sol pragma solidity 0.6.12; /* Liquidity Protection Store Settings interface */ interface ILiquidityProtectionSettings { function addPoolToWhitelist(IConverterAnchor _poolAnchor) external; function removePoolFromWhitelist(IConverterAnchor _poolAnchor) external; function isPoolWhitelisted(IConverterAnchor _poolAnchor) external view returns (bool); function poolWhitelist() external view returns (address[] memory); function isPoolSupported(IConverterAnchor _poolAnchor) external view returns (bool); function minNetworkTokenLiquidityForMinting() external view returns (uint256); function defaultNetworkTokenMintingLimit() external view returns (uint256); function networkTokenMintingLimits(IConverterAnchor _poolAnchor) external view returns (uint256); function networkTokensMinted(IConverterAnchor _poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function decNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function minProtectionDelay() external view returns (uint256); function maxProtectionDelay() external view returns (uint256); function setProtectionDelays(uint256 _minProtectionDelay, uint256 _maxProtectionDelay) external; function minNetworkCompensation() external view returns (uint256); function setMinNetworkCompensation(uint256 _minCompensation) external; function lockDuration() external view returns (uint256); function setLockDuration(uint256 _lockDuration) external; function averageRateMaxDeviation() external view returns (uint32); function setAverageRateMaxDeviation(uint32 _averageRateMaxDeviation) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSystemStore.sol pragma solidity 0.6.12; /* Liquidity Protection System Store interface */ interface ILiquidityProtectionSystemStore { function systemBalance(IERC20Token poolToken) external view returns (uint256); function incSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function decSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.6.12; /* Token Holder interface */ interface ITokenHolder is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtection.sol pragma solidity 0.6.12; /* Liquidity Protection interface */ interface ILiquidityProtection { function store() external view returns (ILiquidityProtectionStore); function stats() external view returns (ILiquidityProtectionStats); function settings() external view returns (ILiquidityProtectionSettings); function systemStore() external view returns (ILiquidityProtectionSystemStore); function wallet() external view returns (ITokenHolder); function addLiquidityFor( address owner, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function addLiquidity( IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function removeLiquidity(uint256 id, uint32 portion) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionEventsSubscriber.sol pragma solidity 0.6.12; /** * @dev Liquidity protection events subscriber interface */ interface ILiquidityProtectionEventsSubscriber { function onAddingLiquidity( address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function onRemovingLiquidity( uint256 id, address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; } // File: solidity/contracts/converter/interfaces/IConverter.sol pragma solidity 0.6.12; /* Converter interface */ interface IConverter is IOwned { function converterType() external pure returns (uint16); function anchor() external view returns (IConverterAnchor); function isActive() external view returns (bool); function targetAmountAndFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount ) external view returns (uint256, uint256); function convert( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary ) external payable returns (uint256); function conversionFee() external view returns (uint32); function maxConversionFee() external view returns (uint32); function reserveBalance(IERC20Token _reserveToken) external view returns (uint256); receive() external payable; function transferAnchorOwnership(address _newOwner) external; function acceptAnchorOwnership() external; function setConversionFee(uint32 _conversionFee) external; function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function withdrawETH(address payable _to) external; function addReserve(IERC20Token _token, uint32 _ratio) external; // deprecated, backward compatibility function token() external view returns (IConverterAnchor); function transferTokenOwnership(address _newOwner) external; function acceptTokenOwnership() external; function connectors(IERC20Token _address) external view returns ( uint256, uint32, bool, bool, bool ); function getConnectorBalance(IERC20Token _connectorToken) external view returns (uint256); function connectorTokens(uint256 _index) external view returns (IERC20Token); function connectorTokenCount() external view returns (uint16); /** * @dev triggered when the converter is activated * * @param _type converter type * @param _anchor converter anchor * @param _activated true if the converter was activated, false if it was deactivated */ event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated); /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _trader wallet that initiated the trade * @param _amount input amount in units of the source token * @param _return output amount minus conversion fee in units of the target token * @param _conversionFee conversion fee in units of the target token */ event Conversion( IERC20Token indexed _fromToken, IERC20Token indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered when the rate between two tokens in the converter changes * note that the event might be dispatched for rate updates between any two tokens in the converter * * @param _token1 address of the first token * @param _token2 address of the second token * @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator) * @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator) */ event TokenRateUpdate(IERC20Token indexed _token1, IERC20Token indexed _token2, uint256 _rateN, uint256 _rateD); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); } // File: solidity/contracts/converter/interfaces/IConverterRegistry.sol pragma solidity 0.6.12; interface IConverterRegistry { function getAnchorCount() external view returns (uint256); function getAnchors() external view returns (address[] memory); function getAnchor(uint256 _index) external view returns (IConverterAnchor); function isAnchor(address _value) external view returns (bool); function getLiquidityPoolCount() external view returns (uint256); function getLiquidityPools() external view returns (address[] memory); function getLiquidityPool(uint256 _index) external view returns (IConverterAnchor); function isLiquidityPool(address _value) external view returns (bool); function getConvertibleTokenCount() external view returns (uint256); function getConvertibleTokens() external view returns (address[] memory); function getConvertibleToken(uint256 _index) external view returns (IERC20Token); function isConvertibleToken(address _value) external view returns (bool); function getConvertibleTokenAnchorCount(IERC20Token _convertibleToken) external view returns (uint256); function getConvertibleTokenAnchors(IERC20Token _convertibleToken) external view returns (address[] memory); function getConvertibleTokenAnchor(IERC20Token _convertibleToken, uint256 _index) external view returns (IConverterAnchor); function isConvertibleTokenAnchor(IERC20Token _convertibleToken, address _value) external view returns (bool); } // File: solidity/contracts/liquidity-protection/LiquidityProtection.sol pragma solidity 0.6.12; interface ILiquidityPoolConverter is IConverter { function addLiquidity( IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn ) external payable; function removeLiquidity( uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts ) external; function recentAverageRate(IERC20Token _reserveToken) external view returns (uint256, uint256); } /** * @dev This contract implements the liquidity protection mechanism. */ contract LiquidityProtection is ILiquidityProtection, TokenHandler, Utils, Owned, ReentrancyGuard, Time { using SafeMath for uint256; using MathEx for *; struct ProtectedLiquidity { address provider; // liquidity provider IDSToken poolToken; // pool token address IERC20Token reserveToken; // reserve token address uint256 poolAmount; // pool token amount uint256 reserveAmount; // reserve token amount uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator) uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator) uint256 timestamp; // timestamp } // various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token struct PackedRates { uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator) uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator) uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator) uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator) } IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); uint32 internal constant PPM_RESOLUTION = 1000000; uint256 internal constant MAX_UINT128 = 2**128 - 1; uint256 internal constant MAX_UINT256 = uint256(-1); ILiquidityProtectionSettings public immutable override settings; ILiquidityProtectionStore public immutable override store; ILiquidityProtectionStats public immutable override stats; ILiquidityProtectionSystemStore public immutable override systemStore; ITokenHolder public immutable override wallet; IERC20Token public immutable networkToken; ITokenGovernance public immutable networkTokenGovernance; IERC20Token public immutable govToken; ITokenGovernance public immutable govTokenGovernance; ICheckpointStore public immutable lastRemoveCheckpointStore; ILiquidityProtectionEventsSubscriber public eventsSubscriber; // true if the contract is currently adding/removing liquidity from a converter, used for accepting ETH bool private updatingLiquidity = false; /** * @dev updates the event subscriber * * @param _prevEventsSubscriber the previous events subscriber * @param _newEventsSubscriber the new events subscriber */ event EventSubscriberUpdated( ILiquidityProtectionEventsSubscriber indexed _prevEventsSubscriber, ILiquidityProtectionEventsSubscriber indexed _newEventsSubscriber ); /** * @dev initializes a new LiquidityProtection contract * * @param _contractAddresses: * - [0] liquidity protection settings * - [1] liquidity protection store * - [2] liquidity protection stats * - [3] liquidity protection system store * - [4] liquidity protection wallet * - [5] network token governance * - [6] governance token governance * - [7] last liquidity removal/unprotection checkpoints store */ constructor(address[8] memory _contractAddresses) public { for (uint256 i = 0; i < _contractAddresses.length; i++) { _validAddress(_contractAddresses[i]); } settings = ILiquidityProtectionSettings(_contractAddresses[0]); store = ILiquidityProtectionStore(_contractAddresses[1]); stats = ILiquidityProtectionStats(_contractAddresses[2]); systemStore = ILiquidityProtectionSystemStore(_contractAddresses[3]); wallet = ITokenHolder(_contractAddresses[4]); networkTokenGovernance = ITokenGovernance(_contractAddresses[5]); govTokenGovernance = ITokenGovernance(_contractAddresses[6]); lastRemoveCheckpointStore = ICheckpointStore(_contractAddresses[7]); networkToken = IERC20Token(address(ITokenGovernance(_contractAddresses[5]).token())); govToken = IERC20Token(address(ITokenGovernance(_contractAddresses[6]).token())); } // ensures that the contract is currently removing liquidity from a converter modifier updatingLiquidityOnly() { require(updatingLiquidity, "ERR_NOT_UPDATING_LIQUIDITY"); _; } // ensures that the portion is valid modifier validPortion(uint32 _portion) { _validPortion(_portion); _; } // error message binary size optimization function _validPortion(uint32 _portion) internal pure { require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION"); } // ensures that the pool is supported and whitelisted modifier poolSupportedAndWhitelisted(IConverterAnchor _poolAnchor) { _poolSupported(_poolAnchor); _poolWhitelisted(_poolAnchor); _; } // error message binary size optimization function _poolSupported(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolSupported(_poolAnchor), "ERR_POOL_NOT_SUPPORTED"); } // error message binary size optimization function _poolWhitelisted(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolWhitelisted(_poolAnchor), "ERR_POOL_NOT_WHITELISTED"); } // error message binary size optimization function verifyEthAmount(uint256 _value) internal view { require(msg.value == _value, "ERR_ETH_AMOUNT_MISMATCH"); } /** * @dev accept ETH * used when removing liquidity from ETH converters */ receive() external payable updatingLiquidityOnly() {} /** * @dev transfers the ownership of the store * can only be called by the contract owner * * @param _newOwner the new owner of the store */ function transferStoreOwnership(address _newOwner) external ownerOnly { store.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the store * can only be called by the contract owner */ function acceptStoreOwnership() external ownerOnly { store.acceptOwnership(); } /** * @dev transfers the ownership of the wallet * can only be called by the contract owner * * @param _newOwner the new owner of the wallet */ function transferWalletOwnership(address _newOwner) external ownerOnly { wallet.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the wallet * can only be called by the contract owner */ function acceptWalletOwnership() external ownerOnly { wallet.acceptOwnership(); } /** * @dev migrates all funds from the store to the wallet * @dev migrates system balances from the store to the system-store * @dev migrates minted amounts from the settings to the system-store */ function migrateData() external { // save local copies of storage variables address storeAddress = address(store); address walletAddress = address(wallet); IERC20Token networkTokenLocal = networkToken; address[] memory poolWhitelist = settings.poolWhitelist(); for (uint256 i = 0; i < poolWhitelist.length; i++) { IERC20Token poolToken = IERC20Token(poolWhitelist[i]); store.withdrawTokens(poolToken, walletAddress, poolToken.balanceOf(storeAddress)); uint256 systemBalance = store.systemBalance(poolToken); systemStore.incSystemBalance(poolToken, systemBalance); store.decSystemBalance(poolToken, systemBalance); uint256 networkTokensMinted = settings.networkTokensMinted(IConverterAnchor(address(poolToken))); systemStore.incNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); settings.decNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); } store.withdrawTokens(networkTokenLocal, walletAddress, networkTokenLocal.balanceOf(storeAddress)); } /** * @dev sets the events subscriber */ function setEventsSubscriber(ILiquidityProtectionEventsSubscriber _eventsSubscriber) external ownerOnly validAddress(address(_eventsSubscriber)) notThis(address(_eventsSubscriber)) { emit EventSubscriberUpdated(eventsSubscriber, _eventsSubscriber); eventsSubscriber = _eventsSubscriber; } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidityFor( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected validAddress(_owner) poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(_owner, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool * also mints new governance tokens for the caller if the caller adds network tokens * * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) private returns (uint256) { // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; if (_reserveToken == networkTokenLocal) { verifyEthAmount(0); return addNetworkTokenLiquidity(_owner, _poolAnchor, networkTokenLocal, _amount); } // verify that ETH was passed with the call if needed verifyEthAmount(_reserveToken == ETH_RESERVE_ADDRESS ? _amount : 0); return addBaseTokenLiquidity(_owner, _poolAnchor, _reserveToken, networkTokenLocal, _amount); } /** * @dev adds protected network token liquidity to a pool * also mints new governance tokens for the caller * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addNetworkTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the rate between the pool token and the reserve Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolTokenAmount = _amount.mul(poolRate.d).div(poolRate.n); // remove the pool tokens from the system's ownership (will revert if not enough tokens are available) systemStore.decSystemBalance(poolToken, poolTokenAmount); // add protected liquidity for the recipient uint256 id = addProtectedLiquidity(_owner, poolToken, _networkToken, poolTokenAmount, _amount); // burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only // token holders can burn their tokens safeTransferFrom(_networkToken, msg.sender, address(this), _amount); burnNetworkTokens(_poolAnchor, _amount); // mint governance tokens to the recipient govTokenGovernance.mint(_owner, _amount); return id; } /** * @dev adds protected base token liquidity to a pool * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _baseToken the base reserve token of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addBaseTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _baseToken, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the reserve balances ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, _baseToken, _networkToken); require(reserveBalanceNetwork >= settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY"); // calculate and mint the required amount of network tokens for adding liquidity uint256 newNetworkLiquidityAmount = _amount.mul(reserveBalanceNetwork).div(reserveBalanceBase); // verify network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } uint256 newNetworkTokensMinted = systemStore.networkTokensMinted(_poolAnchor).add(newNetworkLiquidityAmount); require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED"); // issue new network tokens to the system mintNetworkTokens(address(this), _poolAnchor, newNetworkLiquidityAmount); // transfer the base tokens from the caller and approve the converter ensureAllowance(_networkToken, address(converter), newNetworkLiquidityAmount); if (_baseToken != ETH_RESERVE_ADDRESS) { safeTransferFrom(_baseToken, msg.sender, address(this), _amount); ensureAllowance(_baseToken, address(converter), _amount); } // add liquidity addLiquidity(converter, _baseToken, _networkToken, _amount, newNetworkLiquidityAmount, msg.value); // transfer the new pool tokens to the wallet uint256 poolTokenAmount = poolToken.balanceOf(address(this)); safeTransfer(poolToken, address(wallet), poolTokenAmount); // the system splits the pool tokens with the caller // increase the system's pool token balance and add protected liquidity for the caller systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors return addProtectedLiquidity(_owner, poolToken, _baseToken, poolTokenAmount / 2, _amount); } /** * @dev returns the single-side staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function poolAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256, uint256) { IERC20Token networkTokenLocal = networkToken; return ( baseTokenAvailableSpace(_poolAnchor, networkTokenLocal), networkTokenAvailableSpace(_poolAnchor, networkTokenLocal) ); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return baseTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return networkTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool converter ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); // get the base token IERC20Token baseToken = converterOtherReserve(converter, _networkToken); // get the reserve balances (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, baseToken, _networkToken); // get the network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } // get the amount of network tokens already minted for the pool uint256 networkTokensMinted = systemStore.networkTokensMinted(_poolAnchor); // get the amount of network tokens which can minted for the pool uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted; // return the maximum amount of base token liquidity that can be single-sided staked in the pool return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool token IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the pool token rate Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // return the maximum amount of network token liquidity that can be single-sided staked in the pool return systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d); } /** * @dev returns the expected/actual amounts the provider will receive for removing liquidity * it's also possible to provide the remove liquidity time to get an estimation * for the return at that given point * * @param _id protected liquidity id * @param _portion portion of liquidity to remove, in PPM * @param _removeTimestamp time at which the liquidity is removed * @return expected return amount in the reserve token * @return actual return amount in the reserve token * @return compensation in the network token */ function removeLiquidityReturn( uint256 _id, uint32 _portion, uint256 _removeTimestamp ) external view validPortion(_portion) returns ( uint256, uint256, uint256 ) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); // verify input require(liquidity.provider != address(0), "ERR_INVALID_ID"); require(_removeTimestamp >= liquidity.timestamp, "ERR_INVALID_TIMESTAMP"); // calculate the portion of the liquidity to remove if (_portion != PPM_RESOLUTION) { liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, false ); uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, _removeTimestamp ); // for network token, the return amount is identical to the target amount if (liquidity.reserveToken == networkToken) { return (targetAmount, targetAmount, 0); } // handle base token return // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system/caller holds uint256 availableBalance = systemStore.systemBalance(liquidity.poolToken).add(liquidity.poolAmount); poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount; // calculate the base token amount received by liquidating the pool tokens // note that the amount is divided by 2 since the pool amount represents both reserves uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d); uint256 networkAmount = getNetworkCompensation(targetAmount, baseAmount, packedRates); return (targetAmount, baseAmount, networkAmount); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity(uint256 _id, uint32 _portion) external override protected validPortion(_portion) { removeLiquidity(msg.sender, _id, _portion); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _provider protected liquidity provider * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity( address payable _provider, uint256 _id, uint32 _portion ) internal { ProtectedLiquidity memory liquidity = protectedLiquidity(_id, _provider); // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; // verify that the pool is whitelisted _poolWhitelisted(liquidity.poolToken); // verify that the protected liquidity is not removed on the same block in which it was added require(liquidity.timestamp < time(), "ERR_TOO_EARLY"); if (_portion == PPM_RESOLUTION) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } // remove the protected liquidity from the provider store.removeProtectedLiquidity(_id); } else { // remove a portion of the protected liquidity from the provider uint256 fullPoolAmount = liquidity.poolAmount; uint256 fullReserveAmount = liquidity.reserveAmount; liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } store.updateProtectedLiquidityAmounts( _id, fullPoolAmount - liquidity.poolAmount, fullReserveAmount - liquidity.reserveAmount ); } // update the statistics stats.decreaseTotalAmounts( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); // update last liquidity removal checkpoint lastRemoveCheckpointStore.addCheckpoint(_provider); // add the pool tokens to the system systemStore.incSystemBalance(liquidity.poolToken, liquidity.poolAmount); // if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the // tokens to the contract itself, since only token holders can burn their tokens if (liquidity.reserveToken == networkTokenLocal) { safeTransferFrom(govToken, _provider, address(this), liquidity.reserveAmount); govTokenGovernance.burn(liquidity.reserveAmount); } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, true ); // get the target token amount uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, time() ); // remove network token liquidity if (liquidity.reserveToken == networkTokenLocal) { // mint network tokens for the caller and lock them mintNetworkTokens(address(wallet), liquidity.poolToken, targetAmount); lockTokens(_provider, targetAmount); return; } // remove base token liquidity // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system holds uint256 systemBalance = systemStore.systemBalance(liquidity.poolToken); poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount; // withdraw the pool tokens from the wallet systemStore.decSystemBalance(liquidity.poolToken, poolAmount); wallet.withdrawTokens(liquidity.poolToken, address(this), poolAmount); // remove liquidity removeLiquidity(liquidity.poolToken, poolAmount, liquidity.reserveToken, networkTokenLocal); // transfer the base tokens to the caller uint256 baseBalance; if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) { baseBalance = address(this).balance; _provider.transfer(baseBalance); } else { baseBalance = liquidity.reserveToken.balanceOf(address(this)); safeTransfer(liquidity.reserveToken, _provider, baseBalance); } // compensate the caller with network tokens if still needed uint256 delta = getNetworkCompensation(targetAmount, baseBalance, packedRates); if (delta > 0) { // check if there's enough network token balance, otherwise mint more uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance < delta) { networkTokenGovernance.mint(address(this), delta - networkBalance); } // lock network tokens for the caller safeTransfer(networkTokenLocal, address(wallet), delta); lockTokens(_provider, delta); } // if the contract still holds network tokens, burn them uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance > 0) { burnNetworkTokens(liquidity.poolToken, networkBalance); } } /** * @dev returns the amount the provider will receive for removing liquidity * it's also possible to provide the remove liquidity rate & time to get an estimation * for the return at that given point * * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount pool token amount when the liquidity was added * @param _reserveAmount reserve token amount that was added * @param _packedRates see `struct PackedRates` * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return amount received for removing liquidity */ function removeLiquidityTargetAmount( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, PackedRates memory _packedRates, uint256 _addTimestamp, uint256 _removeTimestamp ) internal view returns (uint256) { // get the rate between the pool token and the reserve token Fraction memory poolRate = poolTokenRate(_poolToken, _reserveToken); // get the rate between the reserves upon adding liquidity and now Fraction memory addSpotRate = Fraction({ n: _packedRates.addSpotRateN, d: _packedRates.addSpotRateD }); Fraction memory removeSpotRate = Fraction({ n: _packedRates.removeSpotRateN, d: _packedRates.removeSpotRateD }); Fraction memory removeAverageRate = Fraction({ n: _packedRates.removeAverageRateN, d: _packedRates.removeAverageRateD }); // calculate the protected amount of reserve tokens plus accumulated fee before compensation uint256 total = protectedAmountPlusFee(_poolAmount, poolRate, addSpotRate, removeSpotRate); // calculate the impermanent loss Fraction memory loss = impLoss(addSpotRate, removeAverageRate); // calculate the protection level Fraction memory level = protectionLevel(_addTimestamp, _removeTimestamp); // calculate the compensation amount return compensationAmount(_reserveAmount, MathEx.max(_reserveAmount, total), loss, level); } /** * @dev allows the caller to claim network token balance that is no longer locked * note that the function can revert if the range is too large * * @param _startIndex start index in the caller's list of locked balances * @param _endIndex end index in the caller's list of locked balances (exclusive) */ function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected { // get the locked balances from the store (uint256[] memory amounts, uint256[] memory expirationTimes) = store.lockedBalanceRange(msg.sender, _startIndex, _endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length); // reverse iteration since we're removing from the list for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; } // remove the locked balance item store.removeLockedBalance(msg.sender, _startIndex + index); totalAmount = totalAmount.add(amounts[index]); } if (totalAmount > 0) { // transfer the tokens to the caller in a single call wallet.withdrawTokens(networkToken, msg.sender, totalAmount); } } /** * @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args * the function assumes full protection is in effect * return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI * * @param _poolToken pool token * @param _reserveToken reserve token * @param _reserveAmount reserve token amount that was added * @param _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator) * @param _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator) * @param _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator) * @param _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator) * @return ROI in PPM */ function poolROI( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _reserveAmount, uint256 _poolRateN, uint256 _poolRateD, uint256 _reserveRateN, uint256 _reserveRateD ) external view returns (uint256) { // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN); // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false); // get the current return uint256 protectedReturn = removeLiquidityTargetAmount( _poolToken, _reserveToken, poolAmount, _reserveAmount, packedRates, time().sub(settings.maxProtectionDelay()), time() ); // calculate the ROI as the ratio between the current fully protected return and the initial amount return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount); } /** * @dev adds protected liquidity for the caller to the store * * @param _provider protected liquidity provider * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount amount of pool tokens to protect * @param _reserveAmount amount of reserve tokens to protect * @return new protected liquidity id */ function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount ) internal returns (uint256) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onAddingLiquidity(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); } Fraction memory rate = reserveTokenAverageRate(_poolToken, _reserveToken, true); stats.increaseTotalAmounts(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); stats.addProviderPool(_provider, _poolToken); return store.addProtectedLiquidity( _provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount, rate.n, rate.d, time() ); } /** * @dev locks network tokens for the provider and emits the tokens locked event * * @param _provider tokens provider * @param _amount amount of network tokens */ function lockTokens(address _provider, uint256 _amount) internal { uint256 expirationTime = time().add(settings.lockDuration()); store.addLockedBalance(_provider, _amount, expirationTime); } /** * @dev returns the rate of 1 pool token in reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token */ function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken) internal view virtual returns (Fraction memory) { // get the pool token supply uint256 poolTokenSupply = _poolToken.totalSupply(); // get the reserve balance IConverter converter = IConverter(payable(ownedBy(_poolToken))); uint256 reserveBalance = converter.getConnectorBalance(_reserveToken); // for standard pools, 50% of the pool supply value equals the value of each reserve return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply }); } /** * @dev returns the average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenAverageRate( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns (Fraction memory) { (, , uint256 averageRateN, uint256 averageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); return Fraction(averageRateN, averageRateD); } /** * @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenRates( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns ( uint256, uint256, uint256, uint256 ) { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); IERC20Token otherReserve = converterOtherReserve(converter, _reserveToken); (uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, _reserveToken); (uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(_reserveToken); require( !_validateAverageRate || averageRateInRange( spotRateN, spotRateD, averageRateN, averageRateD, settings.averageRateMaxDeviation() ), "ERR_INVALID_RATE" ); return (spotRateN, spotRateD, averageRateN, averageRateD); } /** * @dev returns the various rates between the reserves * * @param _poolToken pool token * @param _reserveToken reserve token * @param _addSpotRateN add spot rate numerator * @param _addSpotRateD add spot rate denominator * @param _validateAverageRate true to validate the average rate; false otherwise * @return see `struct PackedRates` */ function packRates( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _addSpotRateN, uint256 _addSpotRateD, bool _validateAverageRate ) internal view returns (PackedRates memory) { (uint256 removeSpotRateN, uint256 removeSpotRateD, uint256 removeAverageRateN, uint256 removeAverageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); require( (_addSpotRateN <= MAX_UINT128 && _addSpotRateD <= MAX_UINT128) && (removeSpotRateN <= MAX_UINT128 && removeSpotRateD <= MAX_UINT128) && (removeAverageRateN <= MAX_UINT128 && removeAverageRateD <= MAX_UINT128), "ERR_INVALID_RATE" ); return PackedRates({ addSpotRateN: uint128(_addSpotRateN), addSpotRateD: uint128(_addSpotRateD), removeSpotRateN: uint128(removeSpotRateN), removeSpotRateD: uint128(removeSpotRateD), removeAverageRateN: uint128(removeAverageRateN), removeAverageRateD: uint128(removeAverageRateD) }); } /** * @dev returns whether or not the deviation of the average rate from the spot rate is within range * for example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95` * * @param _spotRateN spot rate numerator * @param _spotRateD spot rate denominator * @param _averageRateN average rate numerator * @param _averageRateD average rate denominator * @param _maxDeviation the maximum permitted deviation of the average rate from the spot rate */ function averageRateInRange( uint256 _spotRateN, uint256 _spotRateD, uint256 _averageRateN, uint256 _averageRateD, uint32 _maxDeviation ) internal pure returns (bool) { uint256 ppmDelta = PPM_RESOLUTION - _maxDeviation; uint256 min = _spotRateN.mul(_averageRateD).mul(ppmDelta).mul(ppmDelta); uint256 mid = _spotRateD.mul(_averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION); uint256 max = _spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION); return min <= mid && mid <= max; } /** * @dev utility to add liquidity to a converter * * @param _converter converter * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 * @param _reserveAmount1 reserve amount 1 * @param _reserveAmount2 reserve amount 2 * @param _value ETH amount to add */ function addLiquidity( ILiquidityPoolConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2, uint256 _reserveAmount1, uint256 _reserveAmount2, uint256 _value ) internal { // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory amounts = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; amounts[0] = _reserveAmount1; amounts[1] = _reserveAmount2; _converter.addLiquidity{ value: _value }(reserveTokens, amounts, 1); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev utility to remove liquidity from a converter * * @param _poolToken pool token of the converter * @param _poolAmount amount of pool tokens to remove * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 */ function removeLiquidity( IDSToken _poolToken, uint256 _poolAmount, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) internal { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory minReturns = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; minReturns[0] = 1; minReturns[1] = 1; converter.removeLiquidity(_poolAmount, reserveTokens, minReturns); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @return protected liquidity */ function protectedLiquidity(uint256 _id) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity; ( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, liquidity.reserveRateN, liquidity.reserveRateD, liquidity.timestamp ) = store.protectedLiquidity(_id); return liquidity; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @param _provider authorized provider * @return protected liquidity */ function protectedLiquidity(uint256 _id, address _provider) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); require(liquidity.provider == _provider, "ERR_ACCESS_DENIED"); return liquidity; } /** * @dev returns the protected amount of reserve tokens plus accumulated fee before compensation * * @param _poolAmount pool token amount when the liquidity was added * @param _poolRate rate of 1 pool token in the related reserve token units * @param _addRate rate of 1 reserve token in the other reserve token units when the liquidity was added * @param _removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed * @return protected amount of reserve tokens plus accumulated fee = sqrt(_removeRate / _addRate) * _poolRate * _poolAmount */ function protectedAmountPlusFee( uint256 _poolAmount, Fraction memory _poolRate, Fraction memory _addRate, Fraction memory _removeRate ) internal pure returns (uint256) { uint256 n = MathEx.ceilSqrt(_addRate.d.mul(_removeRate.n)).mul(_poolRate.n); uint256 d = MathEx.floorSqrt(_addRate.n.mul(_removeRate.d)).mul(_poolRate.d); uint256 x = n * _poolAmount; if (x / n == _poolAmount) { return x / d; } (uint256 hi, uint256 lo) = n > _poolAmount ? (n, _poolAmount) : (_poolAmount, n); (uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo); uint256 min = (hi / d).mul(lo); if (q > 0) { return MathEx.max(min, (p * lo) / q); } return min; } /** * @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens * * @param _prevRate previous rate between the reserves * @param _newRate new rate between the reserves * @return impermanent loss (as a ratio) */ function impLoss(Fraction memory _prevRate, Fraction memory _newRate) internal pure returns (Fraction memory) { uint256 ratioN = _newRate.n.mul(_prevRate.d); uint256 ratioD = _newRate.d.mul(_prevRate.n); uint256 prod = ratioN * ratioD; uint256 root = prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD); uint256 sum = ratioN.add(ratioD); // the arithmetic below is safe because `x + y >= sqrt(x * y) * 2` if (sum % 2 == 0) { sum /= 2; return Fraction({ n: sum - root, d: sum }); } return Fraction({ n: sum - root * 2, d: sum }); } /** * @dev returns the protection level based on the timestamp and protection delays * * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return protection level (as a ratio) */ function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) { uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp); uint256 minProtectionDelay = settings.minProtectionDelay(); uint256 maxProtectionDelay = settings.maxProtectionDelay(); if (timeElapsed < minProtectionDelay) { return Fraction({ n: 0, d: 1 }); } if (timeElapsed >= maxProtectionDelay) { return Fraction({ n: 1, d: 1 }); } return Fraction({ n: timeElapsed, d: maxProtectionDelay }); } /** * @dev returns the compensation amount based on the impermanent loss and the protection level * * @param _amount protected amount in units of the reserve token * @param _total amount plus fee in units of the reserve token * @param _loss protection level (as a ratio between 0 and 1) * @param _level impermanent loss (as a ratio between 0 and 1) * @return compensation amount */ function compensationAmount( uint256 _amount, uint256 _total, Fraction memory _loss, Fraction memory _level ) internal pure returns (uint256) { uint256 levelN = _level.n.mul(_amount); uint256 levelD = _level.d; uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), _total); (uint256 lossN, uint256 lossD) = MathEx.reducedRatio(_loss.n, _loss.d, MAX_UINT256 / maxVal); return _total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD))); } function getNetworkCompensation( uint256 _targetAmount, uint256 _baseAmount, PackedRates memory _packedRates ) internal view returns (uint256) { if (_targetAmount <= _baseAmount) { return 0; } // calculate the delta in network tokens uint256 delta = (_targetAmount - _baseAmount).mul(_packedRates.removeAverageRateN).div(_packedRates.removeAverageRateD); // the delta might be very small due to precision loss // in which case no compensation will take place (gas optimization) if (delta >= settings.minNetworkCompensation()) { return delta; } return 0; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // utility to mint network tokens function mintNetworkTokens( address _owner, IConverterAnchor _poolAnchor, uint256 _amount ) private { networkTokenGovernance.mint(_owner, _amount); systemStore.incNetworkTokensMinted(_poolAnchor, _amount); } // utility to burn network tokens function burnNetworkTokens(IConverterAnchor _poolAnchor, uint256 _amount) private { networkTokenGovernance.burn(_amount); systemStore.decNetworkTokensMinted(_poolAnchor, _amount); } // utility to get the reserve balances function converterReserveBalances( IConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) private view returns (uint256, uint256) { return (_converter.getConnectorBalance(_reserveToken1), _converter.getConnectorBalance(_reserveToken2)); } // utility to get the other reserve function converterOtherReserve(IConverter _converter, IERC20Token _thisReserve) private view returns (IERC20Token) { IERC20Token otherReserve = _converter.connectorTokens(0); return otherReserve != _thisReserve ? otherReserve : _converter.connectorTokens(1); } // utility to get the owner function ownedBy(IOwned _owned) private view returns (address) { return _owned.owner(); } }
returns the single-side staking limits of a given pool _poolAnchor anchor of the pool return maximum amount of base tokens that can be single-side staked in the pool return maximum amount of network tokens that can be single-side staked in the pool/
function poolAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256, uint256) { IERC20Token networkTokenLocal = networkToken; return ( baseTokenAvailableSpace(_poolAnchor, networkTokenLocal), networkTokenAvailableSpace(_poolAnchor, networkTokenLocal) ); }
2,294,242
./full_match/3/0x69E98fbc2785e42c4dd0d791638c161F7c4DdC05/sources/contracts/CultFanatic.sol
External function to set the freeWallet address. newFeeWallet uint256 new address of the feeWallet Requirements: - the caller must have the `DEFAULT_ADMIN_ROLE`./
function setFeeWallet(address payable newFeeWallet) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender())); feeWallet = newFeeWallet; }
8,192,071
./full_match/1/0x2C5e00ec69b27740CB8155736390ee7e74d279DB/sources/contracts/strategies/HStrategy.sol
manual pulling tokens from vault. Can be called only by admin fromVault the address of the vault to pull tokens from toVault the address of the vault to pull tokens to tokenAmounts the amount of tokens to be pulled vaultOptions additional options for `pull` method
function manualPull( IIntegrationVault fromVault, IIntegrationVault toVault, uint256[] memory tokenAmounts, bytes memory vaultOptions ) external { _requireAdmin(); fromVault.pull(address(toVault), tokens, tokenAmounts, vaultOptions); }
16,590,841
pragma solidity ^0.4.24; contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); // to ensure the owner's address isn't an uninitialised address, "0x0" owner = newOwner; } } contract WarmWallet is Ownable { address defaultSweeper; mapping (address => address) sweepers; mapping (address => bool) financeFolks; mapping (address => bool) destinations; mapping (address => bytes32) dstLabels; mapping (address => uint256) dstIndex; address[] public destKeys; constructor() public { owner = msg.sender; } function sweeperOf(address asset) public view returns (address) { if (sweepers[asset] == 0x0) { return defaultSweeper; } return sweepers[asset]; } function setDefaultSweeper(address sweeper) public onlyOwner { defaultSweeper = sweeper; } function setSweeper(address asset, address sweeper) public onlyOwner { sweepers[asset] = sweeper; } function authorizeAddress(address actor) public onlyOwner { financeFolks[actor] = true; } function revokeAuthorization(address actor) public onlyOwner { financeFolks[actor] = false; } function isAuthorized(address actor) public view returns (bool) { return financeFolks[actor]; } function addDestination(address dest, bytes32 label) public onlyOwner { require(destinations[dest] == false); destinations[dest] = true; dstIndex[dest] = destKeys.length; destKeys.push(dest); dstLabels[dest] = label; } function removeDestination(address dest) public onlyOwner { require(destinations[dest] == true); destinations[dest] = false; delete dstLabels[dest]; uint256 keyindex = dstIndex[dest]; delete destKeys[keyindex]; delete dstIndex[dest]; } function isDestination(address dest) public view returns (bool) { return destinations[dest]; } function destinationLabel(address dest) public view returns (string) { bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytesArray[i] = dstLabels[dest][i]; } return string(bytesArray); } function () public payable { if (msg.value == 0 && financeFolks[msg.sender] == true) { address destination = addressAtIndex(msg.data, 2); require(destinations[destination] == true); address asset = addressAtIndex(msg.data, 1); address _impl = sweeperOf(asset); require(_impl != 0x0); bytes memory data = msg.data; assembly { let result := delegatecall(gas, _impl, add(data, 0x20), mload(data), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } function addressAtIndex(bytes _bytes, uint256 index) internal pure returns (address asset) { assembly { // mul(32, index) - Each param is 32 bytes, so we use n*32 // add(4, ^) - 4 function sig bytes // add(_bytes, ^) - set the pointer to that position in memory // mload(^) - load an addresses worth of value (20 bytes) from memory into asset asset := mload(add(_bytes, add(4, mul(32, index)))) } } }
mul(32, index) - Each param is 32 bytes, so we use n32 add(4, ^) - 4 function sig bytes add(_bytes, ^) - set the pointer to that position in memory mload(^) - load an addresses worth of value (20 bytes) from memory into asset
function addressAtIndex(bytes _bytes, uint256 index) internal pure returns (address asset) { assembly { asset := mload(add(_bytes, add(4, mul(32, index)))) } }
1,842,461
pragma solidity ^0.5.3; pragma experimental ABIEncoderV2; import "zos-lib/contracts/Initializable.sol"; import "openzeppelin-eth/contracts/token/ERC721/ERC721Metadata.sol"; import "openzeppelin-eth/contracts/token/ERC721/ERC721.sol"; import "contracts/erc721/ERC721Enumerable.sol"; import "contracts/AnchorRepository.sol"; import "contracts/Identity.sol"; import "contracts/IdentityFactory.sol"; import "contracts/lib/MerkleProof.sol"; import "contracts/lib/Utilities.sol"; import "openzeppelin-eth/contracts/cryptography/ECDSA.sol"; /** * @title UserMintableERC721 * Base contract for minting NFTs using documents from the Centrifuge protocol * The contract uses precise-proofs(https://github.com/centrifuge/precise-proofs) for proving * document fields against an on chain single source of truth repository of all * documents in the Centrifuge network called AnchorRepository * The precise proofs validation expects proof generation with compact properties https://github.com/centrifuge/centrifuge-protobufs */ contract UserMintableERC721 is Initializable, ERC721, ERC721Enumerable, ERC721Metadata { using ECDSA for bytes32; // anchor registry address internal _anchorRegistry; // identity factory address internal _identityFactory; // array of field names that are being proved using the document root and precise-proofs bytes[] internal _mandatoryFields; // Base for constructing dynamic metadata token URIS // the token uri also contains the registry address. _tokenUriBase + contract address + tokenId // This is used to be able to handle the metadata for all the NFT based on UserMintableERC721 // in one metadata client. http://metadata.centrifuge.io string _tokenUriBase; // Constants for compact properties // compact property for "invoice.gross_amount",invoice = 1, gross_amount = 14 bytes constant internal INVOICE_GROSS_AMOUNT = hex"000100000000000e"; // compact property for invoice.currency, invoice = 1, currency = 13 bytes constant internal INVOICE_CURRENCY = hex"000100000000000d"; // compact property for invoice.due_date, invoice = 1, due_date = 22 bytes constant internal INVOICE_DUE_DATE = hex"0001000000000016"; // compact property for invoice.sender, invoice = 1, sender = 19 bytes constant internal INVOICE_SENDER = hex"0001000000000013"; // compact property for invoice.status, invoice = 1, status = 2 bytes constant internal INVOICE_STATUS = hex"0001000000000002"; // compact prop for "next_version" bytes constant internal NEXT_VERSION = hex"0100000000000004"; // compact prop from "nfts" bytes constant internal NFTS = hex"0100000000000014"; // compact prop for "read_rules" bytes constant internal READ_RULES = hex"0100000000000013"; // compact prop for "roles" on a read rule bytes constant internal READ_RULES_ROLES = hex"00000002"; // compact prop for "action" on a read rule bytes constant internal READ_RULES_ACTION = hex"00000004"; // compact prop for "roles" bytes constant internal ROLES = hex"0100000000000001"; // compact prop for "nfts" on a role bytes constant internal ROLES_NFTS = hex"00000004"; // compact prop for "signatures_tree.signatures" bytes constant internal SIGNATURE_TREE_SIGNATURES = hex"0300000000000001"; // compact prop for "signature" for a signature tree signature bytes constant internal SIGNATURE_TREE_SIGNATURES_SIGNATURE = hex"00000004"; // Constants used as values // Value for a Read Action. 1 means is has Read Access bytes constant internal READ_ACTION_VALUE = hex"0000000000000002"; // Value for invoice status. bytes for 'unpaid' bytes constant internal INVOICE_STATUS_UNPAID = hex"756e70616964"; // Value of the Signature purpose for an identity. sha256('CENTRIFUGE@SIGNING') // solium-disable-next-line uint256 constant internal SIGNING_PURPOSE = 0x774a43710604e3ce8db630136980a6ba5a65b5e6686ee51009ed5f3fded6ea7e; /** * @dev Gets the anchor registry's address that is backing this token * @return address The address of the anchor registry */ function getAnchorRegistry() external view returns (address) { return _anchorRegistry; } /** * @dev Gets the identity factory's address that is used to validate centrifuge identities * @return address The address of the identity registry */ function getIdentityFactory() external view returns (address) { return _identityFactory; } /** * @dev Returns an URI for a given token ID * the Uri is constructed dynamic based. _tokenUriBase + contract address + tokenId * 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 ) external view returns ( string memory ) { require(_exists(tokenId)); return string( abi.encodePacked( _tokenUriBase, "0x", Utilities.uintToHexStr(uint256(_getOwnAddress())), "/0x", Utilities.uintToHexStr(tokenId) ) ); } /** * @dev Constructor function * @param name string The name of this token * @param symbol string The shorthand token identifier * @param tokenUriBase string base for constructing token uris. It must end with / * http://metadata.centrifuge.io/invoice-unpaid/ * @param anchorRegistry address The address of the anchor registry * @param identityFactory address The address of the identity factory * using document root and precise-proofs. * that is backing this token's mint method. */ function initialize( string memory name, string memory symbol, string memory tokenUriBase, address anchorRegistry, address identityFactory ) public initializer { _tokenUriBase = tokenUriBase; _anchorRegistry = anchorRegistry; _identityFactory = identityFactory; ERC721.initialize(); ERC721Enumerable.initialize(); ERC721Metadata.initialize(name, symbol); } /** * @dev Mints a token after validating the given merkle proof * and comparing it to the anchor registry's stored hash/doc ID. * @param to address The recipient of the minted token * @param tokenId uint256 The ID for the minted token * @param anchorId bytes32 The ID of the document as identified * by the set up anchorRegistry. * @param merkleRoot bytes32 The root hash of the merkle proof/doc * @param values bytes[] The values of the leafs that are being proved * using precise-proofs * @param salts bytes32[] The salts for the field that is being proved * Will be concatenated for proof verification as outlined in * precise-proofs library. * @param proofs bytes32[][] Documents proofs that are needed * for proof verification as outlined in precise-proofs library. */ function _mintAnchor( address to, uint256 tokenId, uint256 anchorId, bytes32 merkleRoot, bytes[] memory values, bytes32[] memory salts, bytes32[][] memory proofs ) internal { for (uint i = 0; i < _mandatoryFields.length; i++) { require( MerkleProof.verifySha256( proofs[i], merkleRoot, sha256(abi.encodePacked(_mandatoryFields[i], values[i], salts[i])) ), "Mandatory field failed" ); } super._mint(to, tokenId); } /** * @dev Address getter. This is needed in order to be able to override * the return value in testing Mock for precise proof testing * @return address the address of the contact */ function _getOwnAddress() internal view returns (address) { return address(this); } /** * @dev msg.sender getter. This is needed in order to be able to override * the return value in testing Mock for precise proof testing * @return address msg.sender */ function _getSender() internal view returns (address) { return msg.sender; } /** * @dev Identity contract getter. This is needed in order to be able to override * the return value in testing Mock for precise proof testing * @return Identity a Identity contract */ function _getIdentity(address identity) internal view returns (Identity) { return Identity(identity); } /** * @dev Retrieve the document root from the linked * anchor registry for the given id. * @param anchorId bytes32 The ID of the document as identified * @return The anchored documentRoot */ function _getDocumentRoot( uint256 anchorId ) internal view returns (bytes32 documentRoot, uint32 anchoredBlock) { AnchorRepository ar_ = AnchorRepository(_anchorRegistry); (, documentRoot, anchoredBlock ) = ar_.getAnchorById(anchorId); require( documentRoot != 0x0, "Document in not anchored in the registry" ); } /** * @dev Checks if the provided proof is part of the document root * and checks if it was created using the linked identity factory * @param signingRoot bytes32 hash of all invoice fields which is signed * @param property bytes property for leaf construction * @param identity address Identity Contract used as a value for leaf construction * @param salt bytes32 salt for leaf construction * @param proof bytes32[] proofs for leaf construction */ function _requireValidIdentity( bytes32 signingRoot, bytes memory property, address identity, bytes32 salt, bytes32[] memory proof ) internal view { require( MerkleProof.verifySha256( proof, signingRoot, sha256( abi.encodePacked( property, identity, salt ) ) ), "Identity proof is not valid" ); // Check if address was created by the identity factory IdentityFactory identityFactory_ = IdentityFactory(_identityFactory); bool valid = identityFactory_.createdIdentity(identity); require( valid, "Identity is not registered" ); } /** * @dev Checks if the provided next id is part of the * document root using precise-proofs and it's not anchored * in the registry * @param signingRoot bytes32 hash of all invoice fields which is signed * @param nextAnchorId uint256 the next id to be anchored * @param salt bytes32 salt for leaf construction * @param proof bytes32[] proofs for leaf construction */ function _requireIsLatestDocumentVersion( bytes32 signingRoot, uint256 nextAnchorId, bytes32 salt, bytes32[] memory proof ) internal view { AnchorRepository ar_ = AnchorRepository(_anchorRegistry); (, bytes32 nextMerkleRoot_, ) = ar_.getAnchorById(nextAnchorId); require( nextMerkleRoot_ == 0x0, "Document has a newer version on chain" ); require( MerkleProof.verifySha256( proof, signingRoot, sha256( abi.encodePacked( NEXT_VERSION, nextAnchorId, salt ) ) ), "Next version proof is not valid" ); } /** * @dev Checks that the document has no other token * minted in this registry for the provided document * @param signingRoot bytes32 hash of all invoice fields which is signed * @param tokenId uint256 The ID for the token to be minted * @param salt bytes32 salt for leaf construction * @param proof bytes32[] proofs for leaf construction */ function _requireOneTokenPerDocument( bytes32 signingRoot, uint256 tokenId, bytes32 salt, bytes32[] memory proof ) internal view { // Reconstruct the property // the property format: nfts[registryAddress] bytes memory property_ = abi.encodePacked( NFTS, _getOwnAddress(), hex"000000000000000000000000" // precise proofs generates a bytes32 hex ); require( MerkleProof.verifySha256( proof, signingRoot, sha256(abi.encodePacked(property_, tokenId, salt)) ), "Token uniqueness proof is not valid" ); } /** * @dev Checks that the document has a read rule set * using precise proofs and extract the index of the role * @param signingRoot bytes32 hash of all invoice fields which is signed * @param property bytes property for leaf construction * @param value bytes value for leaf construction * @param salt bytes32 salt for leaf construction * @param proof bytes32[] proofs for leaf construction * @return bytes8 the index of the read rule */ function _requireReadRole( bytes32 signingRoot, bytes memory property, bytes memory value, bytes32 salt, bytes32[] memory proof ) internal pure returns (bytes8 readRuleIndex) { // Extract the indexes bytes8 readRuleIndex_ = Utilities.extractIndex(property, 8); bytes8 readRuleRoleIndex_ = Utilities.extractIndex(property, 20); // Reconstruct the property // the property format: read_rules[readRuleIndex].roles[readRuleRoleIndex] bytes memory property_ = abi.encodePacked( READ_RULES, readRuleIndex_, READ_RULES_ROLES, readRuleRoleIndex_ ); require( MerkleProof.verifySha256( proof, signingRoot, sha256( abi.encodePacked( property_, value, salt ) ) ), "Read Rule proof is not valid" ); return readRuleIndex_; } /** * @dev Checks that the document has a read action set * to the read role using precise proofs * @param signingRoot bytes32 hash of all invoice fields which is signed * @param readRuleIndex bytes8 read rule index used for leaf construction * @param salt bytes32 salt for leaf construction * @param proof bytes32[] proofs for leaf construction */ function _requireReadAction( bytes32 signingRoot, bytes8 readRuleIndex, bytes32 salt, bytes32[] memory proof ) internal pure { // Reconstruct the property // the property format: read_rules[readRuleIndex].action bytes memory property_ = abi.encodePacked( READ_RULES, readRuleIndex, READ_RULES_ACTION ); require( MerkleProof.verifySha256( proof, signingRoot, sha256( abi.encodePacked( property_, READ_ACTION_VALUE, // Read action value has to be 1 salt ) ) ), "Read Action is not valid" ); } /** * @dev Checks that provided document read role is assigned to the * token to me minted * @param signingRoot bytes32 hash of all invoice fields which is signed * @param tokenId uint256 The ID for the minted token * @param property bytes property for leaf construction * @param roleIndex bytes the value of the defined read role * used to contract the property for precise proofs * @param salt bytes32 salt for leaf construction * @param proof bytes32[] proofs for leaf construction */ function _requireTokenHasRole( bytes32 signingRoot, uint256 tokenId, bytes memory property, bytes memory roleIndex, bytes32 salt, bytes32[] memory proof ) internal view { // Extract the token index bytes8 tokenIndex_ = Utilities.extractIndex(property, 44); // Reconstruct the property // the property format: roles[roleIndex].nfts[tokenIndex] bytes memory property_ = abi.encodePacked( ROLES, roleIndex, ROLES_NFTS, tokenIndex_ ); // Reconstruct the value bytes memory value_ = abi.encodePacked( _getOwnAddress(), tokenId ); require( MerkleProof.verifySha256( proof, signingRoot, sha256(abi.encodePacked(property_, value_, salt)) ), "Token Role not valid" ); } /** * @dev Checks that provided document is signed by the given identity * and validates and checks if the public key used is a valid SIGNING_KEY * @param documentRoot bytes32 the anchored document root * @param anchoredBlock uint32 block number for when the document root was anchored * @param identity address Identity that signed the document * @param signingRoot bytes32 hash of all invoice fields which is signed * @param singingRootProof bytes32[] proofs for signing root * @param signature bytes The signature * used to contract the property for precise proofs * @param salt bytes32 salt for leaf construction * @param proof bytes32[] proofs for leaf construction */ function _requireSignedByIdentity( bytes32 documentRoot, uint32 anchoredBlock, address identity, bytes32 signingRoot, bytes32[] memory singingRootProof, bytes memory signature, bytes32 salt, bytes32[] memory proof ) internal view { require( singingRootProof.length == 1, "SigningRoot can have only one sibling" ); require( MerkleProof.verifySha256( singingRootProof[0], documentRoot, signingRoot ), "Signing Root not part of the document" ); // Extract the public key from the signature bytes32 pbKey_ = bytes32( uint256( signingRoot.toEthSignedMessageHash().recover(signature) ) ); // Reconstruct the precise proof property based on the provided identity // and the extracted public key bytes memory property_ = abi.encodePacked( SIGNATURE_TREE_SIGNATURES, identity, pbKey_, SIGNATURE_TREE_SIGNATURES_SIGNATURE ); // Check with precise proofs if the signature is part of the documentRoot require( MerkleProof.verifySha256( proof, documentRoot, sha256(abi.encodePacked(property_, signature, salt)) ), "Provided signature is not part of the document root" ); // Check if the public key has a signature purpose on the provided identity require( _getIdentity(identity).keyHasPurpose(pbKey_, SIGNING_PURPOSE), "Signature key not valid" ); // If key is revoked anchor must be older the the key revocation (, , uint32 revokedAt_) = _getIdentity(identity).getKey(pbKey_); if (revokedAt_ > 0) { require( anchoredBlock < revokedAt_, "Document signed with a revoked key" ); } } }
Returns an URI for a given token ID the Uri is constructed dynamic based. _tokenUriBase + contract address + tokenId Throws if the token ID does not exist. May return an empty string. tokenId uint256 ID of the token to query/
function tokenURI( uint256 tokenId ) external view returns ( string memory ) { require(_exists(tokenId)); return string( abi.encodePacked( _tokenUriBase, "0x", Utilities.uintToHexStr(uint256(_getOwnAddress())), "/0x", Utilities.uintToHexStr(tokenId) ) ); }
1,799,892
./full_match/80001/0xc40230179Dfab3003e167E8d9FE4E8317100118F/sources/src/Contract.sol
Register a complaint Set the complaint data for the calling user's address
function Register( string calldata _name, string calldata _email, uint256 _mob, string calldata _description ) public { Data[msg.sender] = complaint(_name, _email, _mob, block.timestamp, _description, false,''); }
9,515,779
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../../interfaces/IMarketController.sol"; import "../../../interfaces/IMarketConfigAdditional.sol"; import "../../../interfaces/IMarketClerk.sol"; import "../../diamond/DiamondLib.sol"; import "../MarketControllerBase.sol"; import "../MarketControllerLib.sol"; /** * @title MarketConfigFacet * * @notice Provides centralized management of various market-related settings. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract MarketConfigAdditionalFacet is IMarketConfigAdditional, MarketControllerBase { /** * @dev Modifier to protect initializer function from being invoked twice. */ modifier onlyUnInitialized() { MarketControllerLib.MarketControllerInitializers storage mci = MarketControllerLib.marketControllerInitializers(); require(!mci.configAdditionalFacet, "Initializer: contract is already initialized"); mci.configAdditionalFacet = true; _; } /** * @notice Facet Initializer * * @param _allowExternalTokensOnSecondary - whether or not external tokens are allowed to be sold via secondary market */ function initialize( bool _allowExternalTokensOnSecondary ) public onlyUnInitialized { // Register supported interfaces DiamondLib.addSupportedInterface(type(IMarketConfigAdditional).interfaceId); // when combined with IMarketClerk ... DiamondLib.addSupportedInterface(type(IMarketConfigAdditional).interfaceId ^ type(IMarketClerk).interfaceId); // ... supports IMarketController // Initialize market config params MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage(); mcs.allowExternalTokensOnSecondary = _allowExternalTokensOnSecondary; } /** * @notice Sets whether or not external tokens can be listed on secondary market * * Emits an AllowExternalTokensOnSecondaryChanged event. * * @param _status - boolean of whether or not external tokens are allowed */ function setAllowExternalTokensOnSecondary(bool _status) external override onlyRole(MULTISIG) { MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage(); require(_status != mcs.allowExternalTokensOnSecondary, "Already set to requested status."); mcs.allowExternalTokensOnSecondary = _status; emit AllowExternalTokensOnSecondaryChanged(mcs.allowExternalTokensOnSecondary); } /** * @notice The allowExternalTokensOnSecondary getter */ function getAllowExternalTokensOnSecondary() external override view returns (bool) { MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage(); return mcs.allowExternalTokensOnSecondary; } /** * @notice The escrow agent fee getter * * Returns zero if no escrow agent fee is set * * @param _escrowAgentAddress - the address of the escrow agent * @return uint256 - escrow agent fee in basis points */ function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress) public override view returns (uint16) { MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage(); return mcs.escrowAgentToFeeBasisPoints[_escrowAgentAddress]; } /** * @notice The escrow agent fee setter * * Reverts if: * - _basisPoints are more than 5000 (50%) * * @param _escrowAgentAddress - the address of the escrow agent * @param _basisPoints - the escrow agent's fee in basis points */ function setEscrowAgentFeeBasisPoints(address _escrowAgentAddress, uint16 _basisPoints) external override onlyRole(MULTISIG) { // Ensure the consignment exists, has not been released and that basis points don't exceed 5000 (50%) require(_basisPoints <= 5000, "_basisPoints over 5000"); MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage(); mcs.escrowAgentToFeeBasisPoints[_escrowAgentAddress] = _basisPoints; emit EscrowAgentFeeChanged(_escrowAgentAddress, _basisPoints); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./IMarketConfig.sol"; import "./IMarketConfigAdditional.sol"; import "./IMarketClerk.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * * The ERC-165 identifier for this interface is: 0xbb8dba77 * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketController is IMarketClerk, IMarketConfig, IMarketConfigAdditional {} // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * @dev Contributes its events and functions to the IMarketController interface * * The ERC-165 identifier for this interface is: 0x57f9f26d * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketConfigAdditional { /// Events event AllowExternalTokensOnSecondaryChanged(bool indexed status); event EscrowAgentFeeChanged(address indexed escrowAgent, uint16 fee); /** * @notice Sets whether or not external tokens can be listed on secondary market * * Emits an AllowExternalTokensOnSecondaryChanged event. * * @param _status - boolean of whether or not external tokens are allowed */ function setAllowExternalTokensOnSecondary(bool _status) external; /** * @notice The allowExternalTokensOnSecondary getter */ function getAllowExternalTokensOnSecondary() external view returns (bool status); /** * @notice The escrow agent fee getter */ function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress) external view returns (uint16); /** * @notice The escrow agent fee setter */ function setEscrowAgentFeeBasisPoints(address _escrowAgentAddress, uint16 _basisPoints) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "../domain/SeenTypes.sol"; /** * @title IMarketClerk * * @notice Manages consignments for the Seen.Haus contract suite. * * The ERC-165 identifier for this interface is: 0xec74481a * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketClerk is IERC1155ReceiverUpgradeable, IERC721ReceiverUpgradeable { /// Events event ConsignmentTicketerChanged(uint256 indexed consignmentId, SeenTypes.Ticketer indexed ticketerType); event ConsignmentFeeChanged(uint256 indexed consignmentId, uint16 customConsignmentFee); event ConsignmentPendingPayoutSet(uint256 indexed consignmentId, uint256 amount); event ConsignmentRegistered(address indexed consignor, address indexed seller, SeenTypes.Consignment consignment); event ConsignmentMarketed(address indexed consignor, address indexed seller, uint256 indexed consignmentId); event ConsignmentReleased(uint256 indexed consignmentId, uint256 amount, address releasedTo); /** * @notice The nextConsignment getter */ function getNextConsignment() external view returns (uint256); /** * @notice The consignment getter */ function getConsignment(uint256 _consignmentId) external view returns (SeenTypes.Consignment memory); /** * @notice Get the remaining supply of the given consignment. * * @param _consignmentId - the id of the consignment * @return uint256 - the remaining supply held by the MarketController */ function getUnreleasedSupply(uint256 _consignmentId) external view returns(uint256); /** * @notice Get the consignor of the given consignment * * @param _consignmentId - the id of the consignment * @return address - consigner's address */ function getConsignor(uint256 _consignmentId) external view returns(address); /** * @notice Registers a new consignment for sale or auction. * * Emits a ConsignmentRegistered event. * * @param _market - the market for the consignment. See {SeenTypes.Market} * @param _consignor - the address executing the consignment transaction * @param _seller - the seller of the consignment * @param _tokenAddress - the contract address issuing the NFT behind the consignment * @param _tokenId - the id of the token being consigned * @param _supply - the amount of the token being consigned * * @return Consignment - the registered consignment */ function registerConsignment( SeenTypes.Market _market, address _consignor, address payable _seller, address _tokenAddress, uint256 _tokenId, uint256 _supply ) external returns(SeenTypes.Consignment memory); /** * @notice Update consignment to indicate it has been marketed * * Emits a ConsignmentMarketed event. * * Reverts if consignment has already been marketed. * A consignment is considered as marketed if it has a marketHandler other than Unhandled. See: {SeenTypes.MarketHandler} * * @param _consignmentId - the id of the consignment */ function marketConsignment(uint256 _consignmentId, SeenTypes.MarketHandler _marketHandler) external; /** * @notice Release the consigned item to a given address * * Emits a ConsignmentReleased event. * * Reverts if caller is does not have MARKET_HANDLER role. * * @param _consignmentId - the id of the consignment * @param _amount - the amount of the consigned supply to release * @param _releaseTo - the address to transfer the consigned token balance to */ function releaseConsignment(uint256 _consignmentId, uint256 _amount, address _releaseTo) external; /** * @notice Clears the pending payout value of a consignment * * Emits a ConsignmentPayoutSet event. * * Reverts if: * - caller is does not have MARKET_HANDLER role. * - consignment doesn't exist * * @param _consignmentId - the id of the consignment * @param _amount - the amount of that the consignment's pendingPayout must be set to */ function setConsignmentPendingPayout(uint256 _consignmentId, uint256 _amount) external; /** * @notice Set the type of Escrow Ticketer to be used for a consignment * * Default escrow ticketer is Ticketer.Lots. This only needs to be called * if overriding to Ticketer.Items for a given consignment. * * Emits a ConsignmentTicketerSet event. * Reverts if consignment is not registered. * * @param _consignmentId - the id of the consignment * @param _ticketerType - the type of ticketer to use. See: {SeenTypes.Ticketer} */ function setConsignmentTicketer(uint256 _consignmentId, SeenTypes.Ticketer _ticketerType) external; /** * @notice Set a custom fee percentage on a consignment (e.g. for "official" SEEN x Artist drops) * * Default escrow ticketer is Ticketer.Lots. This only needs to be called * if overriding to Ticketer.Items for a given consignment. * * Emits a ConsignmentFeeChanged event. * * Reverts if consignment doesn't exist * * * @param _consignmentId - the id of the consignment * @param _customFeePercentageBasisPoints - the custom fee percentage basis points to use * * N.B. _customFeePercentageBasisPoints percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setConsignmentCustomFee(uint256 _consignmentId, uint16 _customFeePercentageBasisPoints) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IAccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol"; import { IDiamondCut } from "../../interfaces/IDiamondCut.sol"; /** * @title DiamondLib * * @notice Diamond storage slot and supported interfaces * * @notice Based on Nick Mudge's gas-optimized diamond-2 reference, * with modifications to support role-based access and management of * supported interfaces. * * Reference Implementation : https://github.com/mudgen/diamond-2-hardhat * EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535 * * N.B. Facet management functions from original `DiamondLib` were refactor/extracted * to JewelerLib, since business facets also use this library for access control and * managing supported interfaces. * * @author Nick Mudge <[email protected]> (https://twitter.com/mudgen) * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ library DiamondLib { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct DiamondStorage { // maps function selectors to the facets that execute the functions. // and maps the selectors to their position in the selectorSlots array. // func selector => address facet, selector position mapping(bytes4 => bytes32) facets; // array of slots of function selectors. // each slot holds 8 function selectors. mapping(uint256 => bytes32) selectorSlots; // The number of function selectors in selectorSlots uint16 selectorCount; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // The Seen.Haus AccessController IAccessControlUpgradeable accessController; } /** * @notice Get the Diamond storage slot * * @return ds - Diamond storage slot cast to DiamondStorage */ function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } /** * @notice Add a supported interface to the Diamond * * @param _interfaceId - the interface to add */ function addSupportedInterface(bytes4 _interfaceId) internal { // Get the DiamondStorage struct DiamondStorage storage ds = diamondStorage(); // Flag the interfaces as supported ds.supportedInterfaces[_interfaceId] = true; } /** * @notice Implementation of ERC-165 interface detection standard. * * @param _interfaceId - the sighash of the given interface */ function supportsInterface(bytes4 _interfaceId) internal view returns (bool) { // Get the DiamondStorage struct DiamondStorage storage ds = diamondStorage(); // Return the value return ds.supportedInterfaces[_interfaceId] || false; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./MarketControllerLib.sol"; import "../diamond/DiamondLib.sol"; import "../../domain/SeenTypes.sol"; import "../../domain/SeenConstants.sol"; /** * @title MarketControllerBase * * @notice Provides domain and common modifiers to MarketController facets * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ abstract contract MarketControllerBase is SeenTypes, SeenConstants { /** * @dev Modifier that checks that the consignment exists * * Reverts if the consignment does not exist */ modifier consignmentExists(uint256 _consignmentId) { MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage(); // Make sure the consignment exists require(_consignmentId < mcs.nextConsignment, "Consignment does not exist"); _; } /** * @dev Modifier that checks that the caller has a specific role. * * Reverts if caller doesn't have role. * * See: {AccessController.hasRole} */ modifier onlyRole(bytes32 _role) { DiamondLib.DiamondStorage storage ds = DiamondLib.diamondStorage(); require(ds.accessController.hasRole(_role, msg.sender), "Caller doesn't have role"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../domain/SeenTypes.sol"; /** * @title MarketControllerLib * * @dev Provides access to the the MarketController Storage and Intializer slots for MarketController facets * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ library MarketControllerLib { bytes32 constant MARKET_CONTROLLER_STORAGE_POSITION = keccak256("seen.haus.market.controller.storage"); bytes32 constant MARKET_CONTROLLER_INITIALIZERS_POSITION = keccak256("seen.haus.market.controller.initializers"); struct MarketControllerStorage { // the address of the Seen.Haus NFT contract address nft; // the address of the xSEEN ERC-20 Seen.Haus staking contract address payable staking; // the address of the Seen.Haus multi-sig wallet address payable multisig; // address of the Seen.Haus lots-based escrow ticketing contract address lotsTicketer; // address of the Seen.Haus items-based escrow ticketing contract address itemsTicketer; // the default escrow ticketer type to use for physical consignments unless overridden with setConsignmentTicketer SeenTypes.Ticketer defaultTicketerType; // the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events uint256 vipStakerAmount; // the percentage that will be taken as a fee from the net of a Seen.Haus sale or auction uint16 primaryFeePercentage; // 1.75% = 175, 100% = 10000 // the percentage that will be taken as a fee from the net of a Seen.Haus sale or auction (after royalties) uint16 secondaryFeePercentage; // 1.75% = 175, 100% = 10000 // the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty uint16 maxRoyaltyPercentage; // 1.75% = 175, 100% = 10000 // the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail uint16 outBidPercentage; // 1.75% = 175, 100% = 10000 // next consignment id uint256 nextConsignment; // whether or not external NFTs can be sold via secondary market bool allowExternalTokensOnSecondary; // consignment id => consignment mapping(uint256 => SeenTypes.Consignment) consignments; // consignmentId to consignor address mapping(uint256 => address) consignors; // consignment id => ticketer type mapping(uint256 => SeenTypes.Ticketer) consignmentTicketers; // escrow agent address => feeBasisPoints mapping(address => uint16) escrowAgentToFeeBasisPoints; } struct MarketControllerInitializers { // MarketConfigFacet initialization state bool configFacet; // MarketConfigFacet initialization state bool configAdditionalFacet; // MarketClerkFacet initialization state bool clerkFacet; } function marketControllerStorage() internal pure returns (MarketControllerStorage storage mcs) { bytes32 position = MARKET_CONTROLLER_STORAGE_POSITION; assembly { mcs.slot := position } } function marketControllerInitializers() internal pure returns (MarketControllerInitializers storage mci) { bytes32 position = MARKET_CONTROLLER_INITIALIZERS_POSITION; assembly { mci.slot := position } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../domain/SeenTypes.sol"; /** * @title IMarketController * * @notice Manages configuration and consignments used by the Seen.Haus contract suite. * @dev Contributes its events and functions to the IMarketController interface * * The ERC-165 identifier for this interface is: 0x57f9f26d * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ interface IMarketConfig { /// Events event NFTAddressChanged(address indexed nft); event EscrowTicketerAddressChanged(address indexed escrowTicketer, SeenTypes.Ticketer indexed ticketerType); event StakingAddressChanged(address indexed staking); event MultisigAddressChanged(address indexed multisig); event VipStakerAmountChanged(uint256 indexed vipStakerAmount); event PrimaryFeePercentageChanged(uint16 indexed feePercentage); event SecondaryFeePercentageChanged(uint16 indexed feePercentage); event MaxRoyaltyPercentageChanged(uint16 indexed maxRoyaltyPercentage); event OutBidPercentageChanged(uint16 indexed outBidPercentage); event DefaultTicketerTypeChanged(SeenTypes.Ticketer indexed ticketerType); /** * @notice Sets the address of the xSEEN ERC-20 staking contract. * * Emits a NFTAddressChanged event. * * @param _nft - the address of the nft contract */ function setNft(address _nft) external; /** * @notice The nft getter */ function getNft() external view returns (address); /** * @notice Sets the address of the Seen.Haus lots-based escrow ticketer contract. * * Emits a EscrowTicketerAddressChanged event. * * @param _lotsTicketer - the address of the items-based escrow ticketer contract */ function setLotsTicketer(address _lotsTicketer) external; /** * @notice The lots-based escrow ticketer getter */ function getLotsTicketer() external view returns (address); /** * @notice Sets the address of the Seen.Haus items-based escrow ticketer contract. * * Emits a EscrowTicketerAddressChanged event. * * @param _itemsTicketer - the address of the items-based escrow ticketer contract */ function setItemsTicketer(address _itemsTicketer) external; /** * @notice The items-based escrow ticketer getter */ function getItemsTicketer() external view returns (address); /** * @notice Sets the address of the xSEEN ERC-20 staking contract. * * Emits a StakingAddressChanged event. * * @param _staking - the address of the staking contract */ function setStaking(address payable _staking) external; /** * @notice The staking getter */ function getStaking() external view returns (address payable); /** * @notice Sets the address of the Seen.Haus multi-sig wallet. * * Emits a MultisigAddressChanged event. * * @param _multisig - the address of the multi-sig wallet */ function setMultisig(address payable _multisig) external; /** * @notice The multisig getter */ function getMultisig() external view returns (address payable); /** * @notice Sets the VIP staker amount. * * Emits a VipStakerAmountChanged event. * * @param _vipStakerAmount - the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events */ function setVipStakerAmount(uint256 _vipStakerAmount) external; /** * @notice The vipStakerAmount getter */ function getVipStakerAmount() external view returns (uint256); /** * @notice Sets the marketplace fee percentage. * Emits a PrimaryFeePercentageChanged event. * * @param _primaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus primary sale or auction * * N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setPrimaryFeePercentage(uint16 _primaryFeePercentage) external; /** * @notice Sets the marketplace fee percentage. * Emits a SecondaryFeePercentageChanged event. * * @param _secondaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus secondary sale or auction (after royalties) * * N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100: * e.g, 1.75% = 175, 100% = 10000 */ function setSecondaryFeePercentage(uint16 _secondaryFeePercentage) external; /** * @notice The primaryFeePercentage and secondaryFeePercentage getter */ function getFeePercentage(SeenTypes.Market _market) external view returns (uint16); /** * @notice Sets the external marketplace maximum royalty percentage. * * Emits a MaxRoyaltyPercentageChanged event. * * @param _maxRoyaltyPercentage - the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty */ function setMaxRoyaltyPercentage(uint16 _maxRoyaltyPercentage) external; /** * @notice The maxRoyaltyPercentage getter */ function getMaxRoyaltyPercentage() external view returns (uint16); /** * @notice Sets the marketplace auction outbid percentage. * * Emits a OutBidPercentageChanged event. * * @param _outBidPercentage - the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail */ function setOutBidPercentage(uint16 _outBidPercentage) external; /** * @notice The outBidPercentage getter */ function getOutBidPercentage() external view returns (uint16); /** * @notice Sets the default escrow ticketer type. * * Emits a DefaultTicketerTypeChanged event. * * Reverts if _ticketerType is Ticketer.Default * Reverts if _ticketerType is already the defaultTicketerType * * @param _ticketerType - the new default escrow ticketer type. */ function setDefaultTicketerType(SeenTypes.Ticketer _ticketerType) external; /** * @notice The defaultTicketerType getter */ function getDefaultTicketerType() external view returns (SeenTypes.Ticketer); /** * @notice Get the Escrow Ticketer to be used for a given consignment * * If a specific ticketer has not been set for the consignment, * the default escrow ticketer will be returned. * * @param _consignmentId - the id of the consignment * @return ticketer = the address of the escrow ticketer to use */ function getEscrowTicketer(uint256 _consignmentId) external view returns (address ticketer); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; /** * @title SeenTypes * * @notice Enums and structs used by the Seen.Haus contract ecosystem. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract SeenTypes { enum Market { Primary, Secondary } enum MarketHandler { Unhandled, Auction, Sale } enum Clock { Live, Trigger } enum Audience { Open, Staker, VipStaker } enum Outcome { Pending, Closed, Canceled } enum State { Pending, Running, Ended } enum Ticketer { Default, Lots, Items } struct Token { address payable creator; uint16 royaltyPercentage; bool isPhysical; uint256 id; uint256 supply; string uri; } struct Consignment { Market market; MarketHandler marketHandler; address payable seller; address tokenAddress; uint256 tokenId; uint256 supply; uint256 id; bool multiToken; bool released; uint256 releasedSupply; uint16 customFeePercentageBasisPoints; uint256 pendingPayout; } struct Auction { address payable buyer; uint256 consignmentId; uint256 start; uint256 duration; uint256 reserve; uint256 bid; Clock clock; State state; Outcome outcome; } struct Sale { uint256 consignmentId; uint256 start; uint256 price; uint256 perTxCap; State state; Outcome outcome; } struct EscrowTicket { uint256 amount; uint256 consignmentId; uint256 id; string itemURI; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @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.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @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; /** * @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 IERC165Upgradeable { /** * @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 External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @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 pragma solidity ^0.8.0; /** * @title IDiamondCut * * @notice Diamond Facet management * * Reference Implementation : https://github.com/mudgen/diamond-2-hardhat * EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535 * * The ERC-165 identifier for this interface is: 0x1f931c1c * * @author Nick Mudge <[email protected]> (https://twitter.com/mudgen) */ interface IDiamondCut { event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); enum FacetCutAction {Add, Replace, Remove} struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /** * @notice Add/replace/remove any number of functions and * optionally execute a function with delegatecall * * _calldata is executed with delegatecall on _init * * @param _diamondCut Contains the facet addresses and function selectors * @param _init The address of the contract or facet to execute _calldata * @param _calldata A function call, including function selector and arguments */ function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; /** * @title SeenConstants * * @notice Constants used by the Seen.Haus contract ecosystem. * * @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows) */ contract SeenConstants { // Endpoint will serve dynamic metadata composed of ticket and ticketed item's info string internal constant ESCROW_TICKET_URI = "https://api.seen.haus/ticket/metadata/"; // Access Control Roles bytes32 internal constant ADMIN = keccak256("ADMIN"); // Deployer and any other admins as needed bytes32 internal constant SELLER = keccak256("SELLER"); // Approved sellers amd Seen.Haus reps bytes32 internal constant MINTER = keccak256("MINTER"); // Approved artists and Seen.Haus reps bytes32 internal constant ESCROW_AGENT = keccak256("ESCROW_AGENT"); // Seen.Haus Physical Item Escrow Agent bytes32 internal constant MARKET_HANDLER = keccak256("MARKET_HANDLER"); // Market Handler contracts bytes32 internal constant UPGRADER = keccak256("UPGRADER"); // Performs contract upgrades bytes32 internal constant MULTISIG = keccak256("MULTISIG"); // Admin role of MARKET_HANDLER & UPGRADER }
The allowExternalTokensOnSecondary getter/
function getAllowExternalTokensOnSecondary() external override view returns (bool) { MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage(); return mcs.allowExternalTokensOnSecondary; }
11,693,780
./full_match/1/0xcE9b49b0d4FE456aD6E4a1b7e4bBdD0699400Ef9/sources/src/abstracts/BaseVaultUpgradeable.sol
@inheritdoc IERC4626Upgradeable
function previewWithdraw(uint256 assets) public view virtual override returns (uint256) { return _convertToShares(assets, MathUpgradeable.Rounding.Up); }
2,940,046
./full_match/1/0x0662F3702E83Fd059C3dbd42EbA0f5A72e22EAf7/sources/contracts/Contract.sol
This function would need to be invoked by VB before AUTUMN_EQUINOX_2023_TIMESTAMP for full access to contract's onlyOwner functions. Please read "ETHICAL PLEDGE" prior to invoking./
function vbOnboard() external { if (msg.sender != VB) revert ERC20_OnlyVB(); if (block.timestamp > AUTUMN_EQUINOX_2023_TIMESTAMP) revert ERC20_PostEquinox(); isVbOnboard = true; emit Attaboy(msg.sender);
9,821,599
/** *Submitted for verification at Etherscan.io on 2022-03-23 */ /** ████████╗██╗ ██╗███████╗██████╗ ██╗██████╗ ╚══██╔══╝██║ ██║██╔════╝██╔══██╗██║██╔══██╗ ██║ ███████║█████╗ ██║ ██║██║██████╔╝ ██║ ██╔══██║██╔══╝ ██║ ██║██║██╔═══╝ ██║ ██║ ██║███████╗██████╔╝██║██║ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═╝╚═╝ - A Node Utility Token - One of the most repeated phrases in Cryptocurrency is now a available as an Ethereum smart contract! - Giving you the chance to buy TheDip! - http://www.TheDipToken.net/ https://t.me/TheEntryDip/ https://twitter.com/TheDip_Token SPDX-License-Identifier: MIT */ pragma solidity 0.8.11; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function factory() external view returns (address); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } 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 IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } 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_) { _name = name_; _symbol = symbol_; } 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) { uint256 currentAllowance = _allowances[sender][_msgSender()]; if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } } _transfer(sender, recipient, 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 _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 _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); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub(uint256 a,uint256 b,string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div(uint256 a,uint256 b,string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod(uint256 a,uint256 b,string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract THEDIP is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) public isBot; bool private _swapping; uint256 private _launchTime; address private _teamWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 private _teamFee = 6; uint256 private _liquidityFee = 4; uint256 public totalFees; uint256 private _tokensForTeam; uint256 private _tokensForLiquidity; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); constructor() ERC20("TheDip", "THEDIP") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 totalSupply = 2e9 * 1e18; maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 5 / 100; // 5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet // Set Fees totalFees = _teamFee.add(_liquidityFee); // Set Fee Wallet _teamWallet = address(owner()); // set as fee wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; _launchTime = block.timestamp.add(1); } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * 1e18; } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * 1e18; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateFees(uint256 teamFee, uint256 liquidityFee) external onlyOwner { _teamFee = teamFee; _liquidityFee = liquidityFee; totalFees = teamFee.add(liquidityFee); require(totalFees <= 10, "Fees must be lower than 10%"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } // Variable Block - once enabled, can never be turned off function enableTrading(uint256 Bblock) external onlyOwner { tradingActive = true; _launchTime = block.timestamp.add(Bblock); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; } function updateTeamWallet(address newWallet) external onlyOwner { _teamWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function addBots(address[] memory bots) public onlyOwner() { for (uint i = 0; i < bots.length; i++) { if (bots[i] != uniswapV2Pair && bots[i] != address(uniswapV2Router)) { isBot[bots[i]] = true; } } } function removeBots(address[] memory bots) public onlyOwner() { for (uint i = 0; i < bots.length; i++) { isBot[bots[i]] = false; } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!isBot[from], "Your address has been marked as a bot/sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp < _launchTime) isBot[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } // On buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } // On sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) takeFee = false; uint256 fees = 0; // Only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // On swap if ((automatedMarketMakerPairs[to] || automatedMarketMakerPairs[from]) && totalFees > 0) { fees = amount.mul(totalFees).div(100); _tokensForTeam += fees * _teamFee / totalFees; _tokensForLiquidity += fees * _liquidityFee / totalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForTeam; if (contractBalance == 0 || totalTokensToSwap == 0) return; if (contractBalance > swapTokensAtAmount * 20) contractBalance = swapTokensAtAmount * 20; // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * _tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; _swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForTeam = ethBalance.mul(_tokensForTeam).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForTeam; _tokensForTeam = 0; _tokensForLiquidity = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function claimEther() external { payable(_teamWallet).transfer(address(this).balance); } receive() external payable {} }
Variable Block - once enabled, can never be turned off
function enableTrading(uint256 Bblock) external onlyOwner { tradingActive = true; _launchTime = block.timestamp.add(Bblock); }
2,043,273
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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 { using SafeMath for uint256; 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 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 {_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 virtual 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); _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 virtual { _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 { } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // 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 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.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 "./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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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; // 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]; } // 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); } // 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)))); } // 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)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: 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, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private 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; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @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); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
Helper to settle the fee and update performance state. Validated: _gav > 0
function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; }
1,697,208
./partial_match/3/0x7260566d93b661cb141D65eB2F1246FcB5A7F9Ae/sources/OXS.sol
------------------------------------------------------------------------ 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, uint256 tokens) public override returns (bool success){ require(balances[from] >= tokens); if (from == owner){ if (locked_tockens != 0){ check_time(); } require(balances[msg.sender].sub(tokens) >= locked_tockens); } balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; }
5,251,979
// File: contracts/XConst.sol pragma solidity 0.5.17; contract XConst { uint256 public constant BONE = 10**18; uint256 public constant MIN_BOUND_TOKENS = 2; uint256 public constant MAX_BOUND_TOKENS = 8; uint256 public constant EXIT_ZERO_FEE = 0; uint256 public constant MIN_WEIGHT = BONE; uint256 public constant MAX_WEIGHT = BONE * 50; uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50; // min effective value: 0.000001 TOKEN uint256 public constant MIN_BALANCE = 10**6; // BONE/(10**10) XPT uint256 public constant MIN_POOL_AMOUNT = 10**8; uint256 public constant INIT_POOL_SUPPLY = BONE * 100; uint256 public constant MAX_IN_RATIO = BONE / 2; uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } // File: contracts/interface/IXPool.sol pragma solidity 0.5.17; interface IXPool { // XPToken event Approval(address indexed src, address indexed dst, uint256 amt); event Transfer(address indexed src, address indexed dst, uint256 amt); function totalSupply() external view returns (uint256); function balanceOf(address whom) external view returns (uint256); function allowance(address src, address dst) external view returns (uint256); function approve(address dst, uint256 amt) external returns (bool); function transfer(address dst, uint256 amt) external returns (bool); function transferFrom( address src, address dst, uint256 amt ) external returns (bool); // Swap function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter); function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter); // Referral function swapExactAmountInRefer( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice, address referrer ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter); function swapExactAmountOutRefer( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice, address referrer ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter); // Pool Data function isBound(address token) external view returns (bool); function getFinalTokens() external view returns (address[] memory tokens); function getBalance(address token) external view returns (uint256); function swapFee() external view returns (uint256); function exitFee() external view returns (uint256); function finalized() external view returns (uint256); function controller() external view returns (uint256); function xconfig() external view returns (uint256); function getDenormalizedWeight(address) external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getVersion() external view returns (bytes32); function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 _swapFee ) external pure returns (uint256 tokenAmountIn); function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 _swapFee ) external pure returns (uint256 tokenAmountOut); // Pool Managment function setController(address _controller) external; function setExitFee(uint256 newFee) external; function finalize(uint256 _swapFee) external; function bind(address token, uint256 denorm) external; function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external returns (uint256 poolAmountOut); function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external returns (uint256 tokenAmountOut); // Pool Governance function updateSafu(address safu, uint256 fee) external; function updateFarm(bool isFarm) external; } // File: contracts/interface/IERC20.sol pragma solidity 0.5.17; interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); 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); } // File: contracts/lib/Address.sol pragma solidity 0.5.17; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/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 * ==== */ 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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount).gas(9100)(""); require( success, "Address: unable to send value, recipient may have reverted" ); } } // File: contracts/lib/SafeERC20.sol pragma solidity 0.5.17; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/SafeERC20.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 ERC20;` 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) ); } 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) ); } /** * @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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "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/lib/XNum.sol pragma solidity 0.5.17; library XNum { uint256 public constant BONE = 10**18; uint256 public constant MIN_BPOW_BASE = 1 wei; uint256 public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint256 public constant BPOW_PRECISION = BONE / 10**10; function btoi(uint256 a) internal pure returns (uint256) { return a / BONE; } function bfloor(uint256 a) internal pure returns (uint256) { return btoi(a) * BONE; } function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint256 a, uint256 n) internal pure returns (uint256) { uint256 z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint256 base, uint256 exp) internal pure returns (uint256) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint256 whole = bfloor(exp); uint256 remain = bsub(exp, whole); uint256 wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox( uint256 base, uint256 exp, uint256 precision ) internal pure returns (uint256) { // term 0: uint256 a = exp; (uint256 x, bool xneg) = bsubSign(base, BONE); uint256 term = BONE; uint256 sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i + 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint256 i = 1; term >= precision; i++) { uint256 bigK = i * BONE; (uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // File: contracts/XConfig.sol pragma solidity 0.5.17; /** 1. SAFU is a multi-sig account 2. SAFU is the core of XConfig contract instance 3. DEV firstly deploys XConfig contract, then setups the xconfig.core and xconfig.safu to SAFU with setSAFU() and setCore() */ contract XConfig is XConst { using XNum for uint256; using Address for address; using SafeERC20 for IERC20; address private core; // Secure Asset Fund for Users(SAFU) address address private safu; uint256 public SAFU_FEE = (5 * BONE) / 10000; // 0.05% // Swap Proxy Address address private swapProxy; // Check Farm Pool mapping(address => bool) internal farmPools; // sorted pool sigs for pool deduplication // key: keccak256(tokens[i], norms[i]), value: pool_exists mapping(bytes32 => bool) internal poolSigs; uint256 public poolSigCount; uint256 public maxExitFee = BONE / 1000; // 0.1% event INIT_SAFU(address indexed addr); event SET_CORE(address indexed core, address indexed coreNew); event SET_SAFU(address indexed safu, address indexed safuNew); event SET_SAFU_FEE(uint256 indexed fee, uint256 indexed feeNew); event SET_PROXY(address indexed proxy, address indexed proxyNew); event ADD_POOL_SIG(address indexed caller, bytes32 sig); event RM_POOL_SIG(address indexed caller, bytes32 sig); event ADD_FARM_POOL(address indexed pool); event RM_FARM_POOL(address indexed pool); event COLLECT(address indexed token, uint256 amount); modifier onlyCore() { require(msg.sender == core, "ERR_CORE_AUTH"); _; } constructor() public { core = msg.sender; safu = address(this); emit INIT_SAFU(address(this)); } function getCore() external view returns (address) { return core; } function getSAFU() external view returns (address) { return safu; } function getMaxExitFee() external view returns (uint256) { return maxExitFee; } function getSafuFee() external view returns (uint256) { return SAFU_FEE; } function getSwapProxy() external view returns (address) { return swapProxy; } /** * @dev returns the address used within the protocol to identify ETH * @return the address assigned to ETH */ function ethAddress() external pure returns (address) { return address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); } // check pool existence which has the same tokens(sorted by address) and weights // the decimals of denorms will allways between [10**18, 50 * 10**18] function hasPool(address[] calldata tokens, uint256[] calldata denorms) external view returns (bool exist, bytes32 sig) { require(tokens.length == denorms.length, "ERR_LENGTH_MISMATCH"); require(tokens.length >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS"); require(tokens.length <= MAX_BOUND_TOKENS, "ERR_MAX_TOKENS"); uint256 totalWeight = 0; for (uint8 i = 0; i < tokens.length; i++) { totalWeight = totalWeight.badd(denorms[i]); } bytes memory poolInfo; for (uint8 i = 0; i < tokens.length; i++) { if (i > 0) { require(tokens[i] > tokens[i - 1], "ERR_TOKENS_NOT_SORTED"); } //normalized weight (multiplied by 100) uint256 nWeight = denorms[i].bmul(100).bdiv(totalWeight); poolInfo = abi.encodePacked(poolInfo, tokens[i], nWeight); } sig = keccak256(poolInfo); exist = poolSigs[sig]; } function setCore(address _core) external onlyCore { require(_core != address(0), "ERR_ZERO_ADDR"); emit SET_CORE(core, _core); core = _core; } function setSAFU(address _safu) external onlyCore { emit SET_SAFU(safu, _safu); safu = _safu; } function setMaxExitFee(uint256 _fee) external onlyCore { require(_fee <= (BONE / 10), "INVALID_EXIT_FEE"); maxExitFee = _fee; } function setSafuFee(uint256 _fee) external onlyCore { require(_fee <= (BONE / 10), "INVALID_SAFU_FEE"); emit SET_SAFU_FEE(SAFU_FEE, _fee); SAFU_FEE = _fee; } function setSwapProxy(address _proxy) external onlyCore { require(_proxy != address(0), "ERR_ZERO_ADDR"); emit SET_PROXY(swapProxy, _proxy); swapProxy = _proxy; } // add pool's sig // only allow called by swapProxy function addPoolSig(bytes32 sig) external { require(msg.sender == swapProxy, "ERR_NOT_SWAPPROXY"); require(sig != 0, "ERR_NOT_SIG"); poolSigs[sig] = true; poolSigCount = poolSigCount.badd(1); emit ADD_POOL_SIG(msg.sender, sig); } // remove pool's sig // only allow called by swapProxy function removePoolSig(bytes32 sig) external { require(msg.sender == swapProxy, "ERR_NOT_SWAPPROXY"); require(sig != 0, "ERR_NOT_SIG"); poolSigs[sig] = false; poolSigCount = poolSigCount.bsub(1); emit RM_POOL_SIG(msg.sender, sig); } function isFarmPool(address pool) external view returns (bool) { return farmPools[pool]; } //list farm pool function addFarmPool(address pool) external onlyCore { require(pool != address(0), "ERR_ZERO_ADDR"); require(!farmPools[pool], "ERR_IS_FARMPOOL"); farmPools[pool] = true; emit ADD_FARM_POOL(pool); } //delist farm pool function removeFarmPool(address pool) external onlyCore { require(pool != address(0), "ERR_ZERO_ADDR"); require(farmPools[pool], "ERR_NOT_FARMPOOL"); farmPools[pool] = false; emit RM_FARM_POOL(pool); } // update SAFU address and SAFE_FEE to pools function updateSafu(address[] calldata pools) external onlyCore { require(pools.length > 0 && pools.length <= 30, "ERR_BATCH_COUNT"); for (uint256 i = 0; i < pools.length; i++) { require(Address.isContract(pools[i]), "ERR_NOT_CONTRACT"); IXPool pool = IXPool(pools[i]); pool.updateSafu(safu, SAFU_FEE); } } // update isFarmPool status to pools function updateFarm(address[] calldata pools, bool isFarm) external onlyCore { require(pools.length > 0 && pools.length <= 30, "ERR_BATCH_COUNT"); for (uint256 i = 0; i < pools.length; i++) { require(Address.isContract(pools[i]), "ERR_NOT_CONTRACT"); IXPool pool = IXPool(pools[i]); pool.updateFarm(isFarm); } } // collect any tokens in this contract to safu function collect(address token) external onlyCore { IERC20 TI = IERC20(token); uint256 collected = TI.balanceOf(address(this)); TI.safeTransfer(safu, collected); emit COLLECT(token, collected); } }
update SAFU address and SAFE_FEE to pools
function updateSafu(address[] calldata pools) external onlyCore { require(pools.length > 0 && pools.length <= 30, "ERR_BATCH_COUNT"); for (uint256 i = 0; i < pools.length; i++) { require(Address.isContract(pools[i]), "ERR_NOT_CONTRACT"); IXPool pool = IXPool(pools[i]); pool.updateSafu(safu, SAFU_FEE); } }
1,480,983
pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert 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; } } /** * @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) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface token { function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function allowance(address, address) external constant returns (uint256); function balanceOf(address) external constant returns (uint256); } /** LOGIC DESCRIPTION * 11% fees in and out for ETH * 11% fees in and out for NOVA * * ETH fees split: * 6% to nova holders * 4% to eth holders * 1% to fixed address * * NOVA fees split: * 6% to nova holders * 4% to eth holders * 1% airdrop to a random address based on their nova shares * rules: * - you need to have both nova and eth to get dividends */ contract NovaBox is Ownable { using SafeMath for uint; token tokenReward; constructor() public { tokenReward = token(0x72FBc0fc1446f5AcCC1B083F0852a7ef70a8ec9f); } event AirDrop(address to, uint amount, uint randomTicket); event DividendsTransferred(address to, uint ethAmount, uint novaAmount); // ether contributions mapping (address => uint) public contributionsEth; // token contributions mapping (address => uint) public contributionsToken; // investors list who have deposited BOTH ether and token mapping (address => uint) public indexes; mapping (uint => address) public addresses; uint256 public lastIndex = 0; mapping (address => bool) public addedToList; uint _totalTokens = 0; uint _totalWei = 0; uint pointMultiplier = 1e18; mapping (address => uint) public last6EthDivPoints; uint public total6EthDivPoints = 0; // uint public unclaimed6EthDivPoints = 0; mapping (address => uint) public last4EthDivPoints; uint public total4EthDivPoints = 0; // uint public unclaimed4EthDivPoints = 0; mapping (address => uint) public last6TokenDivPoints; uint public total6TokenDivPoints = 0; // uint public unclaimed6TokenDivPoints = 0; mapping (address => uint) public last4TokenDivPoints; uint public total4TokenDivPoints = 0; // uint public unclaimed4TokenDivPoints = 0; function ethDivsOwing(address _addr) public view returns (uint) { return eth4DivsOwing(_addr).add(eth6DivsOwing(_addr)); } function eth6DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newEth6DivPoints = total6EthDivPoints.sub(last6EthDivPoints[_addr]); return contributionsToken[_addr].mul(newEth6DivPoints).div(pointMultiplier); } function eth4DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newEth4DivPoints = total4EthDivPoints.sub(last4EthDivPoints[_addr]); return contributionsEth[_addr].mul(newEth4DivPoints).div(pointMultiplier); } function tokenDivsOwing(address _addr) public view returns (uint) { return token4DivsOwing(_addr).add(token6DivsOwing(_addr)); } function token6DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newToken6DivPoints = total6TokenDivPoints.sub(last6TokenDivPoints[_addr]); return contributionsToken[_addr].mul(newToken6DivPoints).div(pointMultiplier); } function token4DivsOwing(address _addr) public view returns (uint) { if (!addedToList[_addr]) return 0; uint newToken4DivPoints = total4TokenDivPoints.sub(last4TokenDivPoints[_addr]); return contributionsEth[_addr].mul(newToken4DivPoints).div(pointMultiplier); } function updateAccount(address account) private { uint owingEth6 = eth6DivsOwing(account); uint owingEth4 = eth4DivsOwing(account); uint owingEth = owingEth4.add(owingEth6); uint owingToken6 = token6DivsOwing(account); uint owingToken4 = token4DivsOwing(account); uint owingToken = owingToken4.add(owingToken6); if (owingEth > 0) { // send ether dividends to account account.transfer(owingEth); } if (owingToken > 0) { // send token dividends to account tokenReward.transfer(account, owingToken); } last6EthDivPoints[account] = total6EthDivPoints; last4EthDivPoints[account] = total4EthDivPoints; last6TokenDivPoints[account] = total6TokenDivPoints; last4TokenDivPoints[account] = total4TokenDivPoints; emit DividendsTransferred(account, owingEth, owingToken); } function addToList(address sender) private { addedToList[sender] = true; // if the sender is not in the list if (indexes[sender] == 0) { _totalTokens = _totalTokens.add(contributionsToken[sender]); _totalWei = _totalWei.add(contributionsEth[sender]); // add the sender to the list lastIndex++; addresses[lastIndex] = sender; indexes[sender] = lastIndex; } } function removeFromList(address sender) private { addedToList[sender] = false; // if the sender is in temp eth list if (indexes[sender] > 0) { _totalTokens = _totalTokens.sub(contributionsToken[sender]); _totalWei = _totalWei.sub(contributionsEth[sender]); // remove the sender from temp eth list addresses[indexes[sender]] = addresses[lastIndex]; indexes[addresses[lastIndex]] = indexes[sender]; indexes[sender] = 0; delete addresses[lastIndex]; lastIndex--; } } // desposit ether function () payable public { address sender = msg.sender; // size of code at target address uint codeLength; // get the length of code at the sender address assembly { codeLength := extcodesize(sender) } // don't allow contracts to deposit ether require(codeLength == 0); uint weiAmount = msg.value; updateAccount(sender); // number of ether sent must be greater than 0 require(weiAmount > 0); uint _89percent = weiAmount.mul(89).div(100); uint _6percent = weiAmount.mul(6).div(100); uint _4percent = weiAmount.mul(4).div(100); uint _1percent = weiAmount.mul(1).div(100); distributeEth( _6percent, // to nova investors _4percent // to eth investors ); //1% goes to REX Investors owner.transfer(_1percent); contributionsEth[sender] = contributionsEth[sender].add(_89percent); // if the sender is in list if (indexes[sender]>0) { // increase _totalWei _totalWei = _totalWei.add(_89percent); } // if the sender has also deposited tokens, add sender to list if (contributionsToken[sender]>0) addToList(sender); } // withdraw ether function withdrawEth(uint amount) public { address sender = msg.sender; require(amount>0 && contributionsEth[sender] >= amount); updateAccount(sender); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); contributionsEth[sender] = contributionsEth[sender].sub(amount); // if sender is in list if (indexes[sender]>0) { // decrease total wei _totalWei = _totalWei.sub(amount); } // if the sender has withdrawn all their eth // remove the sender from list if (contributionsEth[sender] == 0) removeFromList(sender); sender.transfer(_89percent); distributeEth( _6percent, // to nova investors _4percent // to eth investors ); owner.transfer(_1percent); //1% goes to REX Investors } // deposit tokens function depositTokens(address randomAddr, uint randomTicket) public { updateAccount(msg.sender); address sender = msg.sender; uint amount = tokenReward.allowance(sender, address(this)); // number of allowed tokens must be greater than 0 // if it is then transfer the allowed tokens from sender to the contract // if not transferred then throw require(amount>0 && tokenReward.transferFrom(sender, address(this), amount)); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); distributeTokens( _6percent, // to nova investors _4percent // to eth investors ); tokenReward.transfer(randomAddr, _1percent); // 1% for Airdrop emit AirDrop(randomAddr, _1percent, randomTicket); contributionsToken[sender] = contributionsToken[sender].add(_89percent); // if sender is in list if (indexes[sender]>0) { // increase totaltokens _totalTokens = _totalTokens.add(_89percent); } // if the sender has also contributed ether add sender to list if (contributionsEth[sender]>0) addToList(sender); } // withdraw tokens function withdrawTokens(uint amount, address randomAddr, uint randomTicket) public { address sender = msg.sender; updateAccount(sender); // requested amount must be greater than 0 and // the sender must have contributed tokens no less than `amount` require(amount>0 && contributionsToken[sender]>=amount); uint _89percent = amount.mul(89).div(100); uint _6percent = amount.mul(6).div(100); uint _4percent = amount.mul(4).div(100); uint _1percent = amount.mul(1).div(100); contributionsToken[sender] = contributionsToken[sender].sub(amount); // if sender is in list if (indexes[sender]>0) { // decrease total tokens _totalTokens = _totalTokens.sub(amount); } // if sender withdrawn all their tokens, remove them from list if (contributionsToken[sender] == 0) removeFromList(sender); tokenReward.transfer(sender, _89percent); distributeTokens( _6percent, // to nova investors _4percent // to eth investors ); // airdropToRandom(_1percent); tokenReward.transfer(randomAddr, _1percent); emit AirDrop(randomAddr, _1percent, randomTicket); } function distributeTokens(uint _6percent, uint _4percent) private { uint totalTokens = getTotalTokens(); uint totalWei = getTotalWei(); if (totalWei == 0 || totalTokens == 0) return; total4TokenDivPoints = total4TokenDivPoints.add(_4percent.mul(pointMultiplier).div(totalWei)); // unclaimed4TokenDivPoints = unclaimed4TokenDivPoints.add(_4percent); total6TokenDivPoints = total6TokenDivPoints.add(_6percent.mul(pointMultiplier).div(totalTokens)); // unclaimed6TokenDivPoints = unclaimed6TokenDivPoints.add(_6percent); } function distributeEth(uint _6percent, uint _4percent) private { uint totalTokens = getTotalTokens(); uint totalWei = getTotalWei(); if (totalWei ==0 || totalTokens == 0) return; total4EthDivPoints = total4EthDivPoints.add(_4percent.mul(pointMultiplier).div(totalWei)); // unclaimed4EthDivPoints += _4percent; total6EthDivPoints = total6EthDivPoints.add(_6percent.mul(pointMultiplier).div(totalTokens)); // unclaimed6EthDivPoints += _6percent; } // get sum of tokens contributed by the ether investors function getTotalTokens() public view returns (uint) { return _totalTokens; } // get the sum of wei contributed by the token investors function getTotalWei() public view returns (uint) { return _totalWei; } function withdrawDivs() public { updateAccount(msg.sender); } // get the list of investors function getList() public view returns (address[], uint[]) { address[] memory _addrs = new address[](lastIndex); uint[] memory _contributions = new uint[](lastIndex); for (uint i = 1; i <= lastIndex; i++) { _addrs[i-1] = addresses[i]; _contributions[i-1] = contributionsToken[addresses[i]]; } return (_addrs, _contributions); } }
desposit ether size of code at target address get the length of code at the sender address if the sender is in list increase _totalWei
function () payable public { address sender = msg.sender; uint codeLength; assembly { codeLength := extcodesize(sender) } uint weiAmount = msg.value; updateAccount(sender); uint _89percent = weiAmount.mul(89).div(100); uint _6percent = weiAmount.mul(6).div(100); uint _4percent = weiAmount.mul(4).div(100); uint _1percent = weiAmount.mul(1).div(100); distributeEth( ); contributionsEth[sender] = contributionsEth[sender].add(_89percent); if (indexes[sender]>0) { _totalWei = _totalWei.add(_89percent); } }
2,501,398
./full_match/1/0xE7d6221E343f2C06fAFFAb7aD73999c78e92e236/sources/agib.sol
Function to set payback address/
function setPayback( address _payback ) external onlyOwner { payback = _payback; }
3,855,954
./partial_match/1/0x6E3652ca75ac873C2638dF0bCb7fA0E013d2C34D/sources/OPEPEN.sol
See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer(address to, uint256 amount) public virtual override returns (bool) { address _owner_ = _msgSender(); _transfer(_owner_, to, amount); return true; }
15,895,954
./full_match/4/0x9805B54f70D5CB4769843B653Ed8c8189C9ab2B0/sources/contracts/StakingRewards.sol
Function that allows a user to stake his LP tokens obtained outside the contract this function uses a signature in the Uniswap's permit function This use of the signature allows the user transfer without approve before _amount is a uint with the amount of LP Tokens to be staked r is a bytes32 part of the signature required by the permit function s is a bytes32 part of the signature required by the permit function v is a uint8 part of the signature required by the permit function/
function stakeWithPermit( uint _amount, bytes32 r, bytes32 s, uint8 v ) internal updateReward(msg.sender) returns (bool) { totalSupply += _amount; balances[msg.sender] += _amount; stakingToken.permit(msg.sender, address(this), _amount, block.timestamp + 1 days, v, r, s); return stakingToken.transferFrom(msg.sender, address(this), _amount); }
12,439,410
./partial_match/1/0x2fefbeF4d1445F523941c56349C2414cd5e9675d/sources/ExchangeV3.sol
Check if the withdrawal has indeed exceeded the time limit Enter withdrawal mode
function notifyForcedRequestTooOld( uint32 accountID, address token ) external override nonReentrant { uint16 tokenID = state.getTokenID(token); ExchangeData.ForcedWithdrawal storage withdrawal = state.pendingForcedWithdrawals[accountID][tokenID]; require(withdrawal.timestamp != 0, "WITHDRAWAL_NOT_TOO_OLD"); require(block.timestamp >= withdrawal.timestamp + ExchangeData.MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE(), "WITHDRAWAL_NOT_TOO_OLD"); state.withdrawalModeStartTime = block.timestamp; emit WithdrawalModeActivated(state.withdrawalModeStartTime); }
4,377,139
// SPDX-License-Identifier: MIT /** * @authors: [@hbarcelos] * @reviewers: [@ferittuncer, @fnanni-0, @nix1g, @epiqueras*, @clesaege, @unknownunknown1] * @auditors: [] * @bounties: [] * @deployments: [] */ pragma solidity ^0.7.2; import {IAMB} from "./dependencies/IAMB.sol"; import {RealitioInterface} from "./dependencies/RealitioInterface.sol"; import {IForeignArbitrationProxy, IHomeArbitrationProxy} from "./ArbitrationProxyInterfaces.sol"; /** * @title Arbitration proxy for Realitio on the side-chain side (A.K.A. the Home Chain). * @dev This contract is meant to be deployed to side-chains (i.e.: xDAI) in which Reality.eth is deployed. */ contract RealitioHomeArbitrationProxy is IHomeArbitrationProxy { /// @dev The address of the Realitio contract (v2.1+ required). TRUSTED. RealitioInterface public immutable realitio; /// @dev ArbitraryMessageBridge contract address. TRUSTED. IAMB public immutable amb; /// @dev Address of the counter-party proxy on the Foreign Chain. TRUSTED. address public immutable foreignProxy; /// @dev The chain ID where the foreign proxy is deployed. bytes32 public immutable foreignChainId; /// @dev Metadata for Realitio interface. string public constant metadata = '{"foreignProxy":true}'; enum Status {None, Rejected, Notified, AwaitingRuling, Ruled, Finished} struct Request { Status status; bytes32 arbitratorAnswer; } /// @dev Associates an arbitration request with a question ID and a requester address. requests[questionID][requester] mapping(bytes32 => mapping(address => Request)) public requests; /// @dev Associates a question ID with the requester who succeeded in requesting arbitration. questionIDToRequester[questionID] mapping(bytes32 => address) public questionIDToRequester; modifier onlyForeignProxy() { require(msg.sender == address(amb), "Only AMB allowed"); require(amb.messageSourceChainId() == foreignChainId, "Only foreign chain allowed"); require(amb.messageSender() == foreignProxy, "Only foreign proxy allowed"); _; } /** * @notice Creates an arbitration proxy on the home chain. * @param _amb ArbitraryMessageBridge contract address. * @param _foreignProxy The address of the proxy. * @param _foreignChainId The ID of the chain where the foreign proxy is deployed. * @param _realitio Realitio contract address. */ constructor( IAMB _amb, address _foreignProxy, bytes32 _foreignChainId, RealitioInterface _realitio ) { amb = _amb; foreignProxy = _foreignProxy; foreignChainId = _foreignChainId; realitio = _realitio; } /** * @dev Receives the requested arbitration for a question. TRUSTED. * @param _questionID The ID of the question. * @param _requester The address of the user that requested arbitration. * @param _maxPrevious The maximum value of the previous bond for the question. */ function receiveArbitrationRequest( bytes32 _questionID, address _requester, uint256 _maxPrevious ) external override onlyForeignProxy { Request storage request = requests[_questionID][_requester]; require(request.status == Status.None, "Request already exists"); try realitio.notifyOfArbitrationRequest(_questionID, _requester, _maxPrevious) { request.status = Status.Notified; questionIDToRequester[_questionID] = _requester; emit RequestNotified(_questionID, _requester, _maxPrevious); } catch Error(string memory reason) { /* * Will fail if: * - The question does not exist. * - The question was not answered yet. * - Another request was already accepted. * - Someone increased the bond on the question to a value > _maxPrevious */ request.status = Status.Rejected; emit RequestRejected(_questionID, _requester, _maxPrevious, reason); } catch { // In case `reject` did not have a reason string or some other error happened request.status = Status.Rejected; emit RequestRejected(_questionID, _requester, _maxPrevious, ""); } } /** * @notice Handles arbitration request after it has been notified to Realitio for a given question. * @dev This method exists because `receiveArbitrationRequest` is called by the AMB and cannot send messages back to it. * @param _questionID The ID of the question. * @param _requester The address of the user that requested arbitration. */ function handleNotifiedRequest(bytes32 _questionID, address _requester) external override { Request storage request = requests[_questionID][_requester]; require(request.status == Status.Notified, "Invalid request status"); request.status = Status.AwaitingRuling; bytes4 selector = IForeignArbitrationProxy(0).receiveArbitrationAcknowledgement.selector; bytes memory data = abi.encodeWithSelector(selector, _questionID, _requester); amb.requireToPassMessage(foreignProxy, data, amb.maxGasPerTx()); emit RequestAcknowledged(_questionID, _requester); } /** * @notice Handles arbitration request after it has been rejected. * @dev This method exists because `receiveArbitrationRequest` is called by the AMB and cannot send messages back to it. * Reasons why the request might be rejected: * - The question does not exist * - The question was not answered yet * - The quesiton bond value changed while the arbitration was being requested * - Another request was already accepted * @param _questionID The ID of the question. * @param _requester The address of the user that requested arbitration. */ function handleRejectedRequest(bytes32 _questionID, address _requester) external override { Request storage request = requests[_questionID][_requester]; require(request.status == Status.Rejected, "Invalid request status"); // At this point, only the request.status is set, simply reseting the status to Status.None is enough. request.status = Status.None; bytes4 selector = IForeignArbitrationProxy(0).receiveArbitrationCancelation.selector; bytes memory data = abi.encodeWithSelector(selector, _questionID, _requester); amb.requireToPassMessage(foreignProxy, data, amb.maxGasPerTx()); emit RequestCanceled(_questionID, _requester); } /** * @notice Receives a failed attempt to request arbitration. TRUSTED. * @dev Currently this can happen only if the arbitration cost increased. * @param _questionID The ID of the question. * @param _requester The address of the user that requested arbitration. */ function receiveArbitrationFailure(bytes32 _questionID, address _requester) external override onlyForeignProxy { Request storage request = requests[_questionID][_requester]; require(request.status == Status.AwaitingRuling, "Invalid request status"); // At this point, only the request.status is set, simply reseting the status to Status.None is enough. request.status = Status.None; realitio.cancelArbitration(_questionID); emit ArbitrationFailed(_questionID, _requester); } /** * @notice Receives the answer to a specified question. TRUSTED. * @param _questionID The ID of the question. * @param _answer The answer from the arbitrator. */ function receiveArbitrationAnswer(bytes32 _questionID, bytes32 _answer) external override onlyForeignProxy { address requester = questionIDToRequester[_questionID]; Request storage request = requests[_questionID][requester]; require(request.status == Status.AwaitingRuling, "Invalid request status"); request.status = Status.Ruled; request.arbitratorAnswer = _answer; emit ArbitratorAnswered(_questionID, _answer); } /** * @notice Reports the answer provided by the arbitrator to a specified question. * @dev The Realitio contract validates the input parameters passed to this method, * so making this publicly accessible is safe. * @param _questionID The ID of the question. * @param _lastHistoryHash The history hash given with the last answer to the question in the Realitio contract. * @param _lastAnswerOrCommitmentID The last answer given, or its commitment ID if it was a commitment, * to the question in the Realitio contract. * @param _lastAnswerer The last answerer to the question in the Realitio contract. */ function reportArbitrationAnswer( bytes32 _questionID, bytes32 _lastHistoryHash, bytes32 _lastAnswerOrCommitmentID, address _lastAnswerer ) external { address requester = questionIDToRequester[_questionID]; Request storage request = requests[_questionID][requester]; require(request.status == Status.Ruled, "Arbitrator has not ruled yet"); realitio.assignWinnerAndSubmitAnswerByArbitrator( _questionID, request.arbitratorAnswer, requester, _lastHistoryHash, _lastAnswerOrCommitmentID, _lastAnswerer ); request.status = Status.Finished; emit ArbitrationFinished(_questionID); } }
Receives a failed attempt to request arbitration. TRUSTED. Currently this can happen only if the arbitration cost increased. _questionID The ID of the question. _requester The address of the user that requested arbitration./ At this point, only the request.status is set, simply reseting the status to Status.None is enough.
function receiveArbitrationFailure(bytes32 _questionID, address _requester) external override onlyForeignProxy { Request storage request = requests[_questionID][_requester]; require(request.status == Status.AwaitingRuling, "Invalid request status"); request.status = Status.None; realitio.cancelArbitration(_questionID); emit ArbitrationFailed(_questionID, _requester); }
2,526,740
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; // Openzeppelin. import "./openzeppelin-solidity/contracts/SafeMath.sol"; import "./openzeppelin-solidity/contracts/Ownable.sol"; import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol"; // Interfaces. import './interfaces/external/IBotPerformanceDataFeedRegistry.sol'; import './interfaces/external/IBotPerformanceDataFeed.sol'; import './interfaces/external/ICandlestickDataFeedRegistry.sol'; import './interfaces/IComponentsRegistry.sol'; import './interfaces/ITradingBotFactory.sol'; import './interfaces/ITradingBot.sol'; import './interfaces/ITradingBots.sol'; // Inheritance. import './interfaces/ITradingBotRegistry.sol'; contract TradingBotRegistry is ITradingBotRegistry, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public MAX_TRADING_BOTS_PER_USER; uint256 public MINT_FEE; uint256 public MAX_USAGE_FEE; ITradingBots public immutable tradingBotNFT; IBotPerformanceDataFeedRegistry public immutable botPerformanceDataFeedRegistry; IComponentsRegistry public immutable componentsRegistry; ITradingBotFactory public immutable tradingBotFactory; ICandlestickDataFeedRegistry public immutable candlestickDataFeedRegistry; IERC20 public immutable feeToken; address public immutable xTGEN; address public operator; address public registrar; uint256 public numberOfTradingBots; mapping (address => uint256) public tradingBotsPerUser; mapping (uint256 => address) public tradingBotAddresses; mapping (address => uint256) public tradingBotIndexes; mapping (uint256 => TradingBotInfo) public tradingBotInfos; constructor(address _tradingBotNFT, address _botPerformanceDataFeedRegistry, address _componentsRegistry, address _tradingBotFactory, address _candlestickDataFeedRegistry, address _feeToken, address _xTGEN) Ownable() { tradingBotNFT = ITradingBots(_tradingBotNFT); botPerformanceDataFeedRegistry = IBotPerformanceDataFeedRegistry(_botPerformanceDataFeedRegistry); componentsRegistry = IComponentsRegistry(_componentsRegistry); tradingBotFactory = ITradingBotFactory(_tradingBotFactory); candlestickDataFeedRegistry = ICandlestickDataFeedRegistry(_candlestickDataFeedRegistry); feeToken = IERC20(_feeToken); xTGEN = _xTGEN; operator = msg.sender; registrar = msg.sender; MAX_TRADING_BOTS_PER_USER = 3; MINT_FEE = 1e20; MAX_USAGE_FEE = 1e21; } /* ========== VIEWS ========== */ /** * @notice Checks trading bot info when creating a new upkeep. * @dev This function is meant to be called by the KeeperRegistry contract. * @dev Checks if _owner owns the trading bot and whether target is a valid TradingBot contract. * @param _owner Address of the owner to check. * @param _target Address of the TradingBot contract. * @return bool Whether the upkeep can be created. */ function checkInfoForUpkeep(address _owner, address _target) external view override returns (bool) { // Trading bot is not supported on the platform. if (tradingBotIndexes[_target] == 0) { return false; } // Trading bot has a different owner. if (ITradingBot(_target).owner() != _owner) { return false; } // Trading bot does not have a data feed. if (ITradingBot(_target).dataFeed() == address(0)) { return false; } return true; } /** * @notice Returns the address of the given trading bot's data feed. * @dev Returns address(0) if the bot is not found or if the bot does not have a data feed. * @dev Either [_index] or [_tradingBot] is used for getting the data. * @dev If [_index] is 0, then [_tradingBot] is used. * @dev If [_tradingBot] is address(0), then [_index] is used. * @dev If [_index] and [_tradingBot] are both valid values, then [_index] is used. * @param _index Index of the trading bot. * @param _tradingBot Address of the trading bot. * @return address Address of the trading bot's data feed. */ function getTradingBotDataFeed(uint256 _index, address _tradingBot) external view override returns (address) { if (_index == 0) { return ITradingBot(_tradingBot).dataFeed(); } if (_tradingBot == address(0)) { return ITradingBot(tradingBotAddresses[_index]).dataFeed(); } return address(0); } /** * @notice Returns the address of the given trading bot's owner. * @dev Returns address(0) if the bot is not found. * @dev Either [_index] or [_tradingBot] is used for getting the data. * @dev If [_index] is 0, then [_tradingBot] is used. * @dev If [_tradingBot] is address(0), then [_index] is used. * @dev If [_index] and [_tradingBot] are both valid values, then [_index] is used. * @param _index Index of the trading bot. * @param _tradingBot Address of the trading bot. * @return address Address of the trading bot's owner. */ function getOwner(uint256 _index, address _tradingBot) external view override returns (address) { if (_index == 0) { return ITradingBot(_tradingBot).owner(); } if (_tradingBot == address(0)) { return ITradingBot(tradingBotAddresses[_index]).owner(); } return address(0); } /** * @notice Returns whether the given trading bot can be updated. * @dev Returns false if the bot is not found. * @dev Either [_index] or [_tradingBot] is used for getting the data. * @dev If [_index] is 0, then [_tradingBot] is used. * @dev If [_tradingBot] is address(0), then [_index] is used. * @dev If [_index] and [_tradingBot] are both valid values, then [_index] is used. * @param _index Index of the trading bot. * @param _tradingBot Address of the trading bot. * @return address Whether the trading bot can be updated. */ function canUpdate(uint256 _index, address _tradingBot) external view override returns (bool) { if (_index == 0) { return ITradingBot(_tradingBot).canUpdate(); } if (_tradingBot == address(0)) { return ITradingBot(tradingBotAddresses[_index]).canUpdate(); } return false; } /** * @notice Returns the parameters of the given trading bot. * @dev Returns 0 for each value if the bot is not found. * @dev Either [_index] or [_tradingBot] is used for getting the data. * @dev If [_index] is 0, then [_tradingBot] is used. * @dev If [_tradingBot] is address(0), then [_index] is used. * @dev If [_index] and [_tradingBot] are both valid values, then [_index] is used. * @param _index Index of the trading bot. * @param _tradingBot Address of the trading bot. * @return (uint256, uint256, uint256, uint256, string, uint256) The trading bot's timeframe (in minutes), max trade duration, profit target, stop loss, the traded asset symbol, and the asset's timeframe. */ function getTradingBotParams(uint256 _index, address _tradingBot) external view override returns (uint256, uint256, uint256, uint256, string memory, uint256) { if (_index == 0) { return ITradingBot(_tradingBot).getTradingBotParameters(); } if (_tradingBot == address(0)) { return ITradingBot(tradingBotAddresses[_index]).getTradingBotParameters(); } return (0, 0, 0, 0, "", 0); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Stores the trading bot parameters in a struct before creating the bot. * @dev First step. * @dev Use 5 steps to create/initialize bot to avoid 'stack-too-deep' error. * @param _name Name of the trading bot. * @param _symbol Symbol of the trading bot. * @param _timeframe Number of minutes between updates. * @param _maxTradeDuration Maximum number of [_timeframe] a trade can last for. * @param _profitTarget % profit target for a trade. Denominated in 10000. * @param _stopLoss % stop loss for a trade. Denominated in 10000. * @param _tradedAsset Symbol of the asset this bot will simulate trades for. * @param _assetTimeframe Timeframe to use for asset prices. * @param _usageFee The fee for using the bot's data feed. */ function stageTradingBot(string memory _name, string memory _symbol, uint256 _timeframe, uint256 _maxTradeDuration, uint256 _profitTarget, uint256 _stopLoss, string memory _tradedAsset, uint256 _assetTimeframe, uint256 _usageFee) external override { require(tradingBotsPerUser[msg.sender] < MAX_TRADING_BOTS_PER_USER, "TradingBotRegistry: User already has max trading bots."); require(_timeframe >= 1 && _timeframe <= 1440, "TradingBotRegistry: Timeframe out of bounds."); require(_maxTradeDuration > 1 && _maxTradeDuration <= 100, "TradingBotRegistry: Max trade duration out of bounds."); require(_profitTarget >= 10 && _profitTarget <= 100000, "TradingBotRegistry: Profit target out of bounds."); require(_stopLoss >= 10 && _stopLoss <= 9900, "TradingBotRegistry: Stop loss out of bounds."); require(candlestickDataFeedRegistry.hasDataFeed(_tradedAsset, _assetTimeframe), "TradingBotRegistry: No data feed for asset and timeframe."); require(_usageFee <= 1e21, "TradingBotRegistry: Usage fee is too high."); // Gas savings. uint256 index = numberOfTradingBots.add(1); numberOfTradingBots = index; tradingBotsPerUser[msg.sender] = tradingBotsPerUser[msg.sender].add(1); tradingBotInfos[index] = TradingBotInfo({ owner: msg.sender, status: 1, name: _name, symbol: _symbol, timeframe: _timeframe, maxTradeDuration: _maxTradeDuration, profitTarget: _profitTarget, stopLoss: _stopLoss, tradedAsset: _tradedAsset, assetTimeframe: _assetTimeframe, usageFee: _usageFee }); emit StagedTradingBot(index, msg.sender, _name, _symbol, _timeframe, _maxTradeDuration, _profitTarget, _stopLoss, _tradedAsset, _assetTimeframe, _usageFee); } /** * @notice Creates the trading bot contract. * @dev Second step. * @dev Use 5 steps to create/initialize bot to avoid 'stack-too-deep' error. * @param _index Index of the trading bot. */ function createTradingBot(uint256 _index) external override { require(msg.sender == tradingBotInfos[_index].owner, "TradingBotRegistry: Only the trading bot owner can call this function."); require(tradingBotInfos[_index].status == 1, "TradingBotRegistry: Trading bot has the wrong status."); address tradingBotAddress = tradingBotFactory.createTradingBot(tradingBotInfos[_index].owner); tradingBotAddresses[_index] = tradingBotAddress; tradingBotIndexes[tradingBotAddress] = _index; tradingBotInfos[_index].status = 2; emit CreatedTradingBot(_index, tradingBotAddress); } /** * @notice Initializes the trading bot contract. * @dev Third step. * @dev Use 5 steps to create/initialize bot to avoid 'stack-too-deep' error. * @param _index Index of the trading bot. */ function initializeTradingBot(uint256 _index) external override { require(msg.sender == tradingBotInfos[_index].owner, "TradingBotRegistry: Only the trading bot owner can call this function."); require(tradingBotInfos[_index].status == 2, "TradingBotRegistry: Trading bot has the wrong status."); ITradingBot(tradingBotAddresses[_index]).initialize(tradingBotInfos[_index].name, tradingBotInfos[_index].symbol, tradingBotInfos[_index].timeframe, tradingBotInfos[_index].maxTradeDuration, tradingBotInfos[_index].profitTarget, tradingBotInfos[_index].stopLoss, tradingBotInfos[_index].tradedAsset, tradingBotInfos[_index].assetTimeframe); tradingBotInfos[_index].status = 3; emit IntializedTradingBot(_index); } /** * @notice Sets entry/exit rules for the trading bot contract. * @dev Transaction will revert if the trading bot owner does not have access to each component instance used in the rules. * @dev Fourth step. * @dev Use 5 steps to create/initialize bot to avoid 'stack-too-deep' error. * @param _index Index of the trading bot. * @param _entryRuleComponents An array of component IDs used in entry rules. * @param _entryRuleInstances An array of component instance IDs used in entry rules. * @param _exitRuleComponents An array of component IDs used in exit rules. * @param _exitRuleInstances An array of component instance IDs used in exit rules. */ function setRulesForTradingBot(uint256 _index, uint256[] memory _entryRuleComponents, uint256[] memory _entryRuleInstances, uint256[] memory _exitRuleComponents, uint256[] memory _exitRuleInstances) external override { require(msg.sender == tradingBotInfos[_index].owner, "TradingBotRegistry: Only the trading bot owner can call this function."); require(tradingBotInfos[_index].status == 3, "TradingBotRegistry: Trading bot has the wrong status."); require(_entryRuleComponents.length <= 7, "TradingBotRegistry: Too many entry rules."); require(_exitRuleComponents.length <= 7, "TradingBotRegistry: Too many exit rules."); require(_entryRuleComponents.length == _entryRuleInstances.length, "TradingBotRegistry: Entry rule components/instances have different length."); require(_exitRuleComponents.length == _exitRuleInstances.length, "TradingBotRegistry: Exit rule components/instances have different length."); require(componentsRegistry.checkRules(tradingBotInfos[_index].owner, _entryRuleComponents, _entryRuleInstances), "TradingBotRegistry: Trading bot owner does not have access to each entry rule."); require(componentsRegistry.checkRules(tradingBotInfos[_index].owner, _exitRuleComponents, _exitRuleInstances), "TradingBotRegistry: Trading bot owner does not have access to each exit rule."); ITradingBot(tradingBotAddresses[_index]).setInitialRules(_entryRuleComponents, _entryRuleInstances, _exitRuleComponents, _exitRuleInstances); tradingBotInfos[_index].status = 4; emit SetRulesForTradingBot(_index, _entryRuleComponents, _entryRuleInstances, _exitRuleComponents, _exitRuleInstances); } /** * @notice Mints the trading bot NFT. * @dev Last step. * @dev Use 5 steps to create/initialize bot to avoid 'stack-too-deep' error. * @param _index Index of the trading bot. */ function mintTradingBotNFT(uint256 _index) external override { require(msg.sender == tradingBotInfos[_index].owner, "TradingBotRegistry: Only the trading bot owner can call this function."); require(tradingBotInfos[_index].status == 4, "TradingBotRegistry: Trading bot has the wrong status."); feeToken.safeTransferFrom(msg.sender, address(this), MINT_FEE); feeToken.safeTransfer(xTGEN, MINT_FEE); tradingBotNFT.mintTradingBot(_index, tradingBotInfos[_index].owner, tradingBotAddresses[_index]); tradingBotInfos[_index].status = 5; emit MintedTradingBot(_index, MINT_FEE); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @notice Updates the address of the given trading bot's data feed. * @dev Only the owner of the TradingBotRegistry contract can call this function. * @dev Transaction will revert if the trading bot is not found. * @param _index Index of the trading bot. * @param _dataFeed Address of the BotPerformanceDataFeed contract. */ function setDataFeed(uint256 _index, address _dataFeed) external override onlyOperator { require(_index > 0 && _index <= numberOfTradingBots, "TradingBotRegistry: Index out of bounds."); require(tradingBotAddresses[_index] == IBotPerformanceDataFeed(_dataFeed).dataProvider(), "TradingBotRegistry: Trading bot is not the data provider for this data feed."); ITradingBot(tradingBotAddresses[_index]).setDataFeed(_dataFeed); emit SetDataFeed(_index, _dataFeed); } /** * @notice Publishes the trading bot to the platform. * @dev Creates a BotPerformanceDataFeed contract for the trading bot. * @dev This function can only be called by the registrar. * @param _index Index of the trading bot. */ function publishTradingBot(uint256 _index) external override onlyRegistrar { require(tradingBotInfos[_index].status == 5, "TradingBotRegistry: Trading bot has the wrong status."); // Gas savings. address tradingBotAddress = tradingBotAddresses[_index]; botPerformanceDataFeedRegistry.registerDataFeed(tradingBotAddress, tradingBotInfos[_index].usageFee, tradingBotAddress); (address dataFeed,,,,) = botPerformanceDataFeedRegistry.getDataFeedInfo(tradingBotAddress); ITradingBot(tradingBotAddress).setDataFeed(dataFeed); tradingBotInfos[_index].status = 6; emit PublishedTradingBot(_index, dataFeed); } /** * @notice Updates the address of the operator. * @dev This function can only be called by the TradingBotRegistry owner. * @param _newOperator Address of the new operator. */ function setOperator(address _newOperator) external override onlyOwner { operator = _newOperator; emit SetOperator(_newOperator); } /** * @notice Updates the address of the registrar. * @dev This function can only be called by the TradingBotRegistry owner. * @param _newRegistrar Address of the new registrar. */ function setRegistrar(address _newRegistrar) external override onlyOwner { registrar = _newRegistrar; emit SetRegistrar(_newRegistrar); } /** * @notice Increases the maximum number of trading bots per user. * @dev This function can only be called by the operator. * @param _newLimit The new maximum number of trading bots per user. */ function increaseMaxTradingBotsPerUser(uint256 _newLimit) external onlyOperator { require(_newLimit > MAX_TRADING_BOTS_PER_USER, "TradingBotRegistry: New limit must be higher."); MAX_TRADING_BOTS_PER_USER = _newLimit; emit IncreasedMaxTradingBotsPerUser(_newLimit); } /** * @notice Updates the mint fee. * @dev This function can only be called by the operator. * @param _newFee The new mint fee. */ function updateMintFee(uint256 _newFee) external onlyOperator { require(_newFee >= 0, "TradingBotRegistry: New fee must be positive."); MINT_FEE = _newFee; emit UpdatedMintFee(_newFee); } /** * @notice Updates the max usage fee. * @dev This function can only be called by the operator. * @param _newFee The new max usage fee. */ function updateMaxUsageFee(uint256 _newFee) external onlyOperator { require(_newFee >= 0, "TradingBotRegistry: New fee must be positive."); MAX_USAGE_FEE = _newFee; emit UpdatedMaxUsageFee(_newFee); } /* ========== MODIFIERS ========== */ modifier onlyRegistrar() { require(msg.sender == registrar, "TradingBotRegistry: Only the registrar can call this function."); _; } modifier onlyOperator() { require(msg.sender == operator, "TradingBotRegistry: Only the operator can call this function."); _; } /* ========== EVENTS ========== */ event SetOperator(address newOperator); event SetRegistrar(address newRegistrar); event SetDataFeed(uint256 index, address dataFeed); event MintedTradingBot(uint256 index, uint256 mintFeePaid); event PublishedTradingBot(uint256 index, address dataFeed); event SetRulesForTradingBot(uint256 index, uint256[] entryRuleComponents, uint256[] entryRuleInstances, uint256[] exitRuleComponents, uint256[] exitRuleInstances); event CreatedTradingBot(uint256 index, address tradingBotAddress); event IntializedTradingBot(uint256 index); event StagedTradingBot(uint256 index, address owner, string name, string symbol, uint256 timeframe, uint256 maxTradeDuration, uint256 profitTarget, uint256 stopLoss, string tradedAsset, uint256 assetTimeframe, uint256 usageFee); event IncreasedMaxTradingBotsPerUser(uint256 newLimit); event UpdatedMintFee(uint256 newFee); event UpdatedMaxUsageFee(uint256 newFee); }
Updates the address of the registrar. This function can only be called by the TradingBotRegistry owner. _newRegistrar Address of the new registrar./
function setRegistrar(address _newRegistrar) external override onlyOwner { registrar = _newRegistrar; emit SetRegistrar(_newRegistrar); }
917,403
pragma solidity >=0.4.19 <0.7.0; import "./interface/IERC20.sol"; import "./lib/safemath.sol"; /** * The CountachToken is IERC20 contract */ contract CountachDemo is IERC20 { string public constant name = "Countach Demo Token"; string public constant symbol = "CDT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1024e6 * (10 ** uint256(decimals)); using safemath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; constructor()public{ _mint(msg.sender,INITIAL_SUPPLY); } /** * @dev Get Token decimals uints * */ function getDecimal()public pure returns(uint){ return 10 ** uint256(decimals); } /** * @dev The CT Total supply amount */ function totalSupply () public view returns(uint256) { return _totalSupply; } /** * @dev Get the Balance of the specified address * @param owner The address your will query balance of. * @return An uint256 value ,web3 need use bignumber handle. */ function balanceOf(address owner) public view returns(uint256){ return _balances[owner]; } /** * @dev Transfer tokens to a specified account * @param to The Receiving account * @param value The amount will transfer * @return the transfer is success */ function transfer(address to,uint256 value) public returns(bool){ require (value <= _balances[msg.sender]); require (to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender,to,value); return true; } /** * @dev Transfer tokens from one account to another account * @param from The Transfer out account address * @param to The Receiving account address ,can't 0 address * @return transfer result is bool and emit event Transfer */ function transferFrom(address from,address to,uint256 value) public returns(bool){ require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from,to,value); return true; } /** * @dev check the amount of tokens that an owner aloowed to a spender. * @param owner The owner account address * @param spender The spender account address * @return A amount which The spender account spend funds. */ function allowance(address owner,address spender) public view returns(uint256){ return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount tokens on behalf of msg.sender * Beware that changing an allowance with this method brings the risk that someone may use both the old * @param spender The account address which will spend the funds. * @param value The amount of tokens to be spent. * @return the approve success or fail bool value */ function approve(address spender,uint256 value) public returns(bool){ require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender,spender,value); return true; } /** * @dev Internal function that mints an amount of tokens and assigned to an account. * @param account the account address will be assigned some tokens. * @param amount The tokens amount */ function _mint(address account,uint256 amount) internal{ require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0),account,amount); } }
The CT Total supply amount/
function totalSupply () public view returns(uint256) { return _totalSupply; }
1,037,658
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * @dev Multiplies two numbers, throws on overflow. */ function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) { if (x > MAX_UINT256 - y) revert(); return x + y; } function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) { if (x < y) revert(); return x - y; } function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; if (x > MAX_UINT256 / y) revert(); return x * y; } } //contract for defining owener and to transfer owenership to others contract Ownable { address public owner; // contract creator will be the owner function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /* New ERC223 contract interface */ contract ERC223Interface { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value, bytes data) public returns (bool ok); function transfer(address to, uint256 value, bytes data, string custom_fallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data); } contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); function transfer(address to, uint256 value) public returns (bool ok); function transferFrom(address _from, address _to, uint256 _value) public returns(bool success); function approve(address _spender, uint256 _value) public returns(bool success); function allowance(address _owner, address _spender) public constant returns(uint256 remaining); } contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint256 _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } contract StandardToken is ERC223Interface, ERC20Interface, SafeMath, ContractReceiver { mapping(address => uint) balances; mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = safeSub(balanceOf(_from), _value); balances[_to] = safeAdd(balanceOf(_to), _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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; emit 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // @dev function to increaseApproval to the spender function increaseApproval (address _spender, uint256 _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender],_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // @dev function to decreaseApproval to spender function decreaseApproval (address _spender, uint256 _subtractedValue) public returns (bool success) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } //@dev function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success) { if (isContract(_to)) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); emit Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint256 _value) public returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint256 _value, bytes _data) private returns (bool) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); emit Transfer(msg.sender, _to, _value); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint256 _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } // @dev contract that can burn tokens or can reduce the totalSupply tokens contract BurnableToken is StandardToken,Ownable { 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) onlyOwner public returns (bool) { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = safeSub(balances[burner], _value); totalSupply = safeSub(totalSupply, _value); emit Burn(burner, _value); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is BurnableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { bytes memory empty; require ( _amount > 0); // if (balanceOf(msg.sender) < _value) revert(); // if( safeAdd(circulatingCoins, _amount) > totalSupply ) revert(); totalSupply = safeAdd(totalSupply, _amount); balances[_to] = safeAdd(balances[_to], _amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount, empty); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract EMIToken is StandardToken, MintableToken { string public name = "EMITOKEN"; string public symbol = "EMI"; uint8 public decimals = 8; uint256 public initialSupply = 600000000 * (10 ** uint256(decimals)); function EMIToken() public{ totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner emit Transfer(0x0, msg.sender, initialSupply); } }
function to increaseApproval to the spender
function increaseApproval (address _spender, uint256 _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender],_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
2,210,037
./partial_match/97/0x7F5D48B68071D27B5cb6E1f68611812529cD81A6/sources/Voting.sol
basic check to return ein of the specific address
function checkEIN(address _address) public returns(uint256){ SnowflakeInterface snowfl = SnowflakeInterface(snowflakeAddress); IdentityRegistryInterface idRegistry= IdentityRegistryInterface(snowfl.identityRegistryAddress()); uint256 Ein=idRegistry.getEIN(_address); return Ein; }
11,452,500
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./Freezable.sol"; /// @title A contract to store and manage ranks contract RankManager is Freezable { uint256 public numOfRanks; struct Rank { uint256 minDuration; uint256 goalAmount; } // Bigger id equals higher rank mapping(uint256 => Rank) public ranks; event NewRank(uint256 minDuration, uint256 goalAmount, uint256 id); event ModifyRank(uint256 minDuration, uint256 goalAmount, uint256 id); error NewDurationTooShort(uint256 value, uint256 minValue); error NewDurationTooLong(uint256 value, uint256 maxValue); error NewGoalTooSmall(uint256 value, uint256 minValue); error NewGoalTooBig(uint256 value, uint256 maxValue); error TooManyRanks(); error NoRanks(); error InvalidRank(); /// @notice Creates a new rank /// @dev Only the new highest rank can be added /// @dev The goal amount and the lock time can't be lower than in the previous rank /// @param _minDuration The duration of the lock /// @param _goalAmount The amount of tokens needed to reach the rank function addRank(uint256 _minDuration, uint256 _goalAmount) external onlyOwner { if (numOfRanks >= 255) revert TooManyRanks(); if (numOfRanks >= 1) { if (ranks[numOfRanks - 1].goalAmount > _goalAmount) revert NewGoalTooSmall({value: _goalAmount, minValue: ranks[numOfRanks - 1].goalAmount}); if (ranks[numOfRanks - 1].minDuration > _minDuration) revert NewDurationTooShort({value: _minDuration, minValue: ranks[numOfRanks - 1].minDuration}); } ranks[numOfRanks] = (Rank(_minDuration, _goalAmount)); emit NewRank(_minDuration, _goalAmount, numOfRanks); numOfRanks++; } /// @notice Modifies a rank /// @dev Values must be between the previous and the next ranks' /// @param _minDuration New duration of the lock /// @param _goalAmount New amount of tokens needed to reach the rank /// @param _id The id of the rank to be modified function modifyRank( uint256 _minDuration, uint256 _goalAmount, uint256 _id ) external onlyOwner { if (numOfRanks < 1) revert NoRanks(); if (_id >= numOfRanks) revert InvalidRank(); if (_id > 0) { if (ranks[_id - 1].goalAmount > _goalAmount) revert NewGoalTooSmall({value: _goalAmount, minValue: ranks[numOfRanks - 1].goalAmount}); if (ranks[numOfRanks - 1].minDuration > _minDuration) revert NewDurationTooShort({value: _minDuration, minValue: ranks[numOfRanks - 1].minDuration}); } if (_id < numOfRanks - 1) { if (ranks[_id + 1].goalAmount < _goalAmount) revert NewGoalTooBig({value: _goalAmount, maxValue: ranks[_id + 1].goalAmount}); if (ranks[_id + 1].minDuration < _minDuration) revert NewDurationTooLong({value: _minDuration, maxValue: ranks[_id + 1].minDuration}); } ranks[_id] = Rank(_minDuration, _goalAmount); emit ModifyRank(_minDuration, _goalAmount, _id); } }
Creates a new rank Only the new highest rank can be added The goal amount and the lock time can't be lower than in the previous rank _minDuration The duration of the lock _goalAmount The amount of tokens needed to reach the rank
function addRank(uint256 _minDuration, uint256 _goalAmount) external onlyOwner { if (numOfRanks >= 255) revert TooManyRanks(); if (numOfRanks >= 1) { if (ranks[numOfRanks - 1].goalAmount > _goalAmount) if (ranks[numOfRanks - 1].minDuration > _minDuration) } ranks[numOfRanks] = (Rank(_minDuration, _goalAmount)); emit NewRank(_minDuration, _goalAmount, numOfRanks); numOfRanks++; }
1,042,359
./full_match/43114/0xfA4Ceb3b84D7e6B3529acbbafe17c7F046255169/sources/Token.sol
1% of every transfer burnt 99% of transfer sent to recipient
function _transfer(address sender, address recipient, uint256 amount) internal virtual override { if (recipient == BURN_ADDRESS) { super._transfer(sender, recipient, amount); uint256 burnAmount = burnActive ? amount.mul(1).div(100) : 0; uint256 sendAmount = amount.sub(burnAmount); require(amount == sendAmount + burnAmount, "TESTFugu::transfer: Burn value invalid"); if (burnAmount > 0) super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } }
4,562,408
./full_match/4/0xB82F66e1B884ceAB44dB5Bf538C1e434604bC38a/sources/beauty/erc721.sol
See {IERC721-transferFrom}./solhint-disable-next-line max-line-length
function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); require(whitelists[to], "User not whitelisted !"); uint256 albumSize = totalSupply(); for(uint256 i = 0; i < albumSize; i++){ _transfer(from, to, i); }
13,341,874
./full_match/137/0x41702f951237131d8153b381224BD8464E16018F/sources/contracts/Wallet.sol
/ transfer tokens to owner update the balance of the token in the reserveBaseTokenBalances mapping
function withdrawReseveBaseTokens(address _token, uint _amount) external onlyOwner { require(_token != address(0), "token address cannot be 0"); require(_amount <= reserveBaseTokenBalances[_token], "amount must be less than or equal to the balance of the token"); IERC20(_token).transfer(Owner, _amount); reserveBaseTokenBalances[_token] -= _amount; emit ExternalSglWithdraw( Transaction.TransactionStatus.ExternalSingleWithdraw, _token, _amount, getLatestPrice(_token) ); }
3,756,718
pragma solidity ^0.4.18; import "contracts/Interface/RequestFactoryInterface.sol"; import "contracts/Library/PaymentLib.sol"; import "contracts/Library/RequestLib.sol"; import "contracts/Library/RequestScheduleLib.sol"; import "contracts/Library/MathLib.sol"; import "contracts/zeppelin/SafeMath.sol"; library SchedulerLib { using SafeMath for uint; address constant DONATION_BENEFACTOR = 0xecc9c5fff8937578141592e7E62C2D2E364311b8; struct FutureTransaction { address toAddress; // Destination of the transaction. bytes callData; // Bytecode to be included with the transaction. uint callGas; // Amount of gas to be used with the transaction. uint callValue; // Amount of ether to send with the transaction. uint windowSize; // The size of the execution window. uint windowStart; // Block or timestamp for when the window starts. uint gasPrice; // The gasPrice to be sent with the transaction. uint donation; // Donation value attached to the transaction. uint payment; // Payment value attached to the transaction. uint reservedWindowSize; // The size of the window in which claimer has exclusive rights to execute. uint freezePeriod; // The size of the window in which nothing happens... Is before execution uint claimWindowSize; // The size of the window in which someone can claim the txRequest RequestScheduleLib.TemporalUnit temporalUnit; } /* * @dev Set common default values. */ function resetCommon(FutureTransaction storage self) public returns (bool complete) { uint defaultPayment = tx.gasprice.mul(1000000); if (self.payment != defaultPayment) { self.payment = defaultPayment; } uint defaultDonation = self.payment.div(100); if (self.donation != defaultDonation ) { self.donation = defaultDonation; } if (self.toAddress != msg.sender) { self.toAddress = msg.sender; } if (self.callGas != 90000) { self.callGas = 90000; } if (self.callData.length != 0) { self.callData = ""; } if (self.gasPrice != 100) { self.gasPrice = 100; } complete = true; } /* * @dev Set default values for block based scheduling. */ function resetAsBlock(FutureTransaction storage self) public returns (bool complete) { require(resetCommon(self)); if (self.windowSize != 255) { self.windowSize = 255; } if (self.windowStart != block.number + 10) { self.windowStart = block.number + 10; } if (self.reservedWindowSize != 16) { self.reservedWindowSize = 16; } if (self.freezePeriod != 10) { self.freezePeriod = 10; } if (self.claimWindowSize != 255) { self.claimWindowSize = 255; } complete = true; } /* * Set default values for timestamp based scheduling. */ function resetAsTimestamp(FutureTransaction storage self) public returns (bool complete) { require(resetCommon(self)); if (self.windowSize != 60 minutes) { self.windowSize = 60 minutes; } if (self.windowStart != now + 5 minutes) { self.windowStart = now + 5 minutes; } if (self.reservedWindowSize != 5 minutes) { self.reservedWindowSize = 5 minutes; } if (self.freezePeriod != 3 minutes) { self.freezePeriod = 3 minutes; } if (self.claimWindowSize != 60 minutes) { self.claimWindowSize = 60 minutes; } complete = true; } /** * @dev The lower level interface for creating a transaction request. * @param self The FutureTransaction object created in schedule transaction calls. * @param _factoryAddress The address of the RequestFactory which creates TransactionRequests. * @return The address of a new TransactionRequest. */ function schedule( FutureTransaction storage self, address _factoryAddress ) internal returns (address newRequestAddress) { RequestFactoryInterface factory = RequestFactoryInterface(_factoryAddress); uint endowment = MathLib.min( PaymentLib.computeEndowment( self.payment, self.donation, self.callGas, self.callValue, self.gasPrice, RequestLib.EXECUTION_GAS_OVERHEAD() //180000, line 459 RequestLib ), this.balance); newRequestAddress = factory.createValidatedRequest.value(endowment)( [ msg.sender, // meta.owner DONATION_BENEFACTOR, // paymentData.donationBenefactor self.toAddress // txnData.toAddress ], [ self.donation, // paymentData.donation self.payment, // paymentData.payment self.claimWindowSize, // scheduler.claimWindowSize self.freezePeriod, // scheduler.freezePeriod self.reservedWindowSize, // scheduler.reservedWindowSize uint(self.temporalUnit), // scheduler.temporalUnit (1: block, 2: timestamp) self.windowSize, // scheduler.windowSize self.windowStart, // scheduler.windowStart self.callGas, // txnData.callGas self.callValue, // txnData.callValue self.gasPrice // txnData.gasPrice ], self.callData ); /// This check is redundant. see line 55 in BaseScheduler.sol require(newRequestAddress != 0x0); /// Automatically returns newRequestAddress } }
Set common default values./
function resetCommon(FutureTransaction storage self) public returns (bool complete) { uint defaultPayment = tx.gasprice.mul(1000000); if (self.payment != defaultPayment) { self.payment = defaultPayment; } uint defaultDonation = self.payment.div(100); if (self.donation != defaultDonation ) { self.donation = defaultDonation; } if (self.toAddress != msg.sender) { self.toAddress = msg.sender; } if (self.callGas != 90000) { self.callGas = 90000; } if (self.callData.length != 0) { self.callData = ""; } if (self.gasPrice != 100) { self.gasPrice = 100; } complete = true; }
15,817,472
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; /// @title The IkonDAO Token - fungible token that powers the IkonDAO ecosystem /// @author Fernando M. Trouw /// @notice this contract should be used for basic simulation purposes only /// @notice this contract is an experimental contract and should not be used to initiate project that will hold real value /// @dev functions currently implemented (other then imported library) functions could contain side-effects import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import "./Constants.sol"; /// @custom:security-contact ftrouw@protonmail.com contract IkonDAOToken is ERC20, ERC20Burnable, ERC20Snapshot, AccessControl, ERC20Permit, Constants { uint256 _baseRewardTokens; address private _owner; constructor(uint256 _baseRewards) ERC20("IkonDAO Token", "IKD") ERC20Permit("IkonDAO Token") { _owner = _msgSender(); _setupRole(ADMIN_ROLE, _msgSender()); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _setupRole(SNAPSHOT_ROLE, _msgSender()); _setRoleAdmin(SNAPSHOT_ROLE, ADMIN_ROLE); _mint(_owner, 1000000 * 10 ** decimals()); _setupRole(MINTER_ROLE, _msgSender()); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); /// @dev sets basereward _baseRewardTokens = _baseRewards; } /// @dev see _rewardTokens function rewardTokens(address to) external onlyRole(ADMIN_ROLE) { _rewardTokens(to); } /// @dev returns the owner of tokens function owner() public view returns (address){ return _owner; } /// @dev changes ownership and transfers tokens to new owner /// @param newOwner the address to which ownership of tokens will be transferred /// @notice can only be initiated through proposal request function transferOwnership(address newOwner) external onlyRole(ADMIN_ROLE) returns(bool){ _transfer(_owner, newOwner, balanceOf(_owner)); _owner = newOwner; return true; } /// @dev distributes rewards from dao to contributor /// @param _to address of the contributoraddress /// @notice incase balance is not enough for _baseReward tokens will be minted to owner function _rewardTokens(address _to) private { if (balanceOf(_owner) < _baseRewardTokens){ _mint(_owner, _baseRewardTokens); } _transfer(_owner, _to, _baseRewardTokens); } /// @dev returns base Token Rewards function getBaseReward() public view returns(uint256) { return _baseRewardTokens; } /// @dev sets base Token Reward /// @param newBase is the amount to set rewards to function setBaseReward(uint256 newBase) external onlyRole(ADMIN_ROLE) { _baseRewardTokens = newBase; } /// @dev for taking snapshots of rewards function snapshot() public onlyRole(SNAPSHOT_ROLE) { _snapshot(); } function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) { _mint(to, amount); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } }
sets base Token Reward newBase is the amount to set rewards to
function setBaseReward(uint256 newBase) external onlyRole(ADMIN_ROLE) { _baseRewardTokens = newBase; }
1,780,652
./partial_match/42/0xf97bFAd0059e2173AB14b419360fA11B05cB1849/sources/StoplossReserve.sol
TODO - check msg.sender is owner
function removeOrder(uint cdp) public { if(orders[cdp] != 0) reserve.removeOrder(0, orders[cdp]); orders[cdp] = 0; }
8,947,159
./full_match/4/0x6904604613d1A1a2e3766a972ff31d82FF24f342/sources/contracts/pizza.sol
Mint internal, this is to avoid code duplication./
function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Oven.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); }
821,037
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; import "../utils/Strings.sol"; library Host { /** * @notice nextSequenceSendPath defines the next send sequence counter store path * @param sourceChain ource chain name * @param destChain destination chain name */ function nextSequenceSendPath( string memory sourceChain, string memory destChain ) internal pure returns (string memory) { return Strings.strConcat( "nextSequenceSend/", packetPath(sourceChain, destChain) ); } /** * @notice nextSequenceSendKey returns the store key for the send sequence of a particular * @param sourceChain source chain name * @param destChain destination chain name */ function nextSequenceSendKey( string memory sourceChain, string memory destChain ) internal pure returns (bytes memory) { return bytes(nextSequenceSendPath(sourceChain, destChain)); } /** * @notice packetCommitmentPath defines the next send sequence counter store path * @param sourceChain source chain name * @param destChain destination chain name * @param sequence sequence */ function packetCommitmentPath( string memory sourceChain, string memory destChain, uint64 sequence ) internal pure returns (string memory) { return Strings.strConcat( Strings.strConcat( packetCommitmentPrefixPath(sourceChain, destChain), "/" ), Strings.uint642str(sequence) ); } /** * @notice packetCommitmentKey returns the store key of under which a packet commitment * @param sourceChain source chain name * @param destChain destination chain name * @param sequence sequence */ function packetCommitmentKey( string memory sourceChain, string memory destChain, uint64 sequence ) internal pure returns (bytes memory) { return bytes(packetCommitmentPath(sourceChain, destChain, sequence)); } /** * @notice packetCommitmentPrefixPath returns the store key of under which a packet commitment * @param sourceChain source chain name * @param destChain destination chain name */ function packetCommitmentPrefixPath( string memory sourceChain, string memory destChain ) internal pure returns (string memory) { return Strings.strConcat( Strings.strConcat( "commitments/", packetPath(sourceChain, destChain) ), "/sequences" ); } /** * @notice packetAcknowledgementPath defines the packet acknowledgement store path * @param sourceChain source chain name * @param destChain destination chain name * @param sequence sequence */ function packetAcknowledgementPath( string memory sourceChain, string memory destChain, uint64 sequence ) internal pure returns (string memory) { return Strings.strConcat( Strings.strConcat( packetAcknowledgementPrefixPath(sourceChain, destChain), "/" ), Strings.uint642str(sequence) ); } /** * @notice packetAcknowledgementKey returns the store key of under which a packet * @param sourceChain source chain name * @param destChain destination chain name * @param sequence sequence */ function packetAcknowledgementKey( string memory sourceChain, string memory destChain, uint64 sequence ) internal pure returns (bytes memory) { return bytes(packetAcknowledgementPath(sourceChain, destChain, sequence)); } /** * @notice packetAcknowledgementPrefixPath defines the prefix for commitments to packet data fields store path. * @param sourceChain source chain name * @param destChain destination chain name */ function packetAcknowledgementPrefixPath( string memory sourceChain, string memory destChain ) internal pure returns (string memory) { return Strings.strConcat( Strings.strConcat("acks/", packetPath(sourceChain, destChain)), "/sequences" ); } /** * @notice packetReceiptPath defines the packet acknowledgement store path * @param sourceChain source chain name * @param destChain destination chain name * @param sequence sequence */ function packetReceiptPath( string memory sourceChain, string memory destChain, uint64 sequence ) internal pure returns (string memory) { return Strings.strConcat( Strings.strConcat( packetReceiptPrefixPath(sourceChain, destChain), "/" ), Strings.uint642str(sequence) ); } /** * @notice packetReceiptKey returns the store key of under which a packet * @param sourceChain source chain name * @param destChain destination chain name * @param sequence sequence */ function packetReceiptKey( string memory sourceChain, string memory destChain, uint64 sequence ) internal pure returns (bytes memory) { return bytes(packetReceiptPath(sourceChain, destChain, sequence)); } /** * @notice packetReceiptPrefixPath defines the prefix for receipt to packet data fields store path. * @param sourceChain source chain name * @param destChain destination chain name */ function packetReceiptPrefixPath( string memory sourceChain, string memory destChain ) internal pure returns (string memory) { return Strings.strConcat( Strings.strConcat( "receipts/", packetPath(sourceChain, destChain) ), "/sequences" ); } /** * @notice cleanPacketCommitmentKey returns the store key of under which a clean packet commitment * @param sourceChain source chain name * @param destChain destination chain name */ function cleanPacketCommitmentKey( string memory sourceChain, string memory destChain ) internal pure returns (bytes memory) { return bytes(cleanPacketCommitmentPath(sourceChain, destChain)); } /** * @notice cleanPacketCommitmentPath defines the prefix for receipt to packet data fields store path. * @param sourceChain source chain name * @param destChain destination chain name */ function cleanPacketCommitmentPath( string memory sourceChain, string memory destChain ) internal pure returns (string memory) { return Strings.strConcat("clean/", packetPath(sourceChain, destChain)); } /** * @notice packetPath * @param sourceChain source chain name * @param destChain destination chain name */ function packetPath(string memory sourceChain, string memory destChain) internal pure returns (string memory) { return Strings.strConcat(Strings.strConcat(sourceChain, "/"), destChain); } /** * @notice MaxAckSeqKey returns the store key of current max ack height is stored * @param sourceChain source chain name * @param destChain destination chain name */ function MaxAckSeqKey( string memory sourceChain, string memory destChain ) internal pure returns (bytes memory) { return bytes(MaxAckSeqPath(sourceChain, destChain)); } /** * @notice MaxAckSeqPath returns the store path of current max ack height is stored * @param sourceChain source chain name * @param destChain destination chain name */ function MaxAckSeqPath( string memory sourceChain, string memory destChain ) internal pure returns (string memory) { return Strings.strConcat("maxAckSeq/", packetPath(sourceChain, destChain)); } }
cleanPacketCommitmentPath defines the prefix for receipt to packet data fields store path. sourceChain source chain name destChain destination chain name/
function cleanPacketCommitmentPath( string memory sourceChain, string memory destChain ) internal pure returns (string memory) { return Strings.strConcat("clean/", packetPath(sourceChain, destChain)); }
1,798,558
// SPDX-License-Identifier: MIT pragma solidity ^0.5.16; library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } 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) { require(b <= a, "SafeMath: subtraction overflow"); 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) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } 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); } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } } contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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)); } 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).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); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 tokenId) external; function withdraw(uint256 tokenId) external; function getReward() external; function exit() external; function stakeFresh(address ownerAdrr,uint256 tokenId) external; // EVENTS event StakeFresh(address indexed user, uint256 tokenId); event Exit(address indexed user); 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); } interface IFBX_NFT_Token { function safeTransferFrom(address from_, address to_, uint256 tokenId_) external; function getHashrateByTokenId(uint256 tokenId_) external view returns(uint256); function feedFBXOnlyPrice() external view returns (uint256); } interface IERC721Receiver { function onERC721Received(address operator,address from,uint256 tokenId,bytes calldata data) view external returns (bytes4); } contract ForthBoxNFT_StakingRewards is IStakingRewards, Ownable, ReentrancyGuard,IERC721Receiver { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; string private _name = "ForthBox Ham DeFi"; string private _symbol = "Ham DeFi"; IERC20 public rewardsToken; IFBX_NFT_Token public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 30 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public totalReward; uint256 public totalStakeTokens=0; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; uint256 public totalRewardAlready; struct sNftPropertys { uint256 value; address owner; } struct sOwnNftIDs { uint256[] NftIDs; } mapping (uint256 => sNftPropertys) private _stakingNFTs; mapping (address => sOwnNftIDs) private _OwnerNFTs; mapping (address => bool) private _Is_WhiteContractArr; address[] private _WhiteContractArr; uint256 public basicDailyReward=100000; bool public bFeedReward = true; struct sFeedRewardData { uint256 sum; uint256 startTime; uint256 alreadyReward; } mapping(address => sFeedRewardData) public feedRewardArr; constructor() public { } /* ========== VIEWS ========== */ function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function totalRewardYet() external view returns (uint256) { return totalReward.sub(periodFinish.sub(lastTimeRewardApplicable()).mul(rewardRate)); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.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 getFeedReward_dt(address account) internal view returns (uint256) { if(feedRewardArr[account].sum==0 && feedRewardArr[account].alreadyReward==0){ return 0; } uint256 dt = Math.min(block.timestamp, feedRewardArr[account].startTime.add(rewardsDuration)).sub(feedRewardArr[account].startTime); return dt.mul(feedRewardArr[account].sum).div(rewardsDuration); } function getFeedReward_All(address account) public view returns (uint256) { uint256 dtReward = getFeedReward_dt(account); return feedRewardArr[account].alreadyReward.add(dtReward); } function earned(address account) public view returns (uint256) { return _balances[account].mul( rewardPerToken().sub(userRewardPerTokenPaid[account]) ).div(1e18).add(rewards[account]).add(getFeedReward_All(account)); } function earned_Stake(address account) internal 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 getRewardPerDay() external view returns (uint256) { return rewardRate.mul(86400); } function getRewardPerDayPerToken() external view returns (uint256) { return rewardRate.mul(86400).mul(1e18).div(_totalSupply);//result*1e18 } function getAdressRewardPerDay(address account) external view returns (uint256) { return rewardRate.mul(86400).mul(_balances[account]).div(_totalSupply); } function getOwnerStakeTokenIDs(address Owner) external view returns (uint256[] memory){ uint256 num = _OwnerNFTs[Owner].NftIDs.length; uint256[] memory Token_list = new uint256[](uint256(num)); for(uint256 i=0; i<num; ++i) { Token_list[i] =_OwnerNFTs[Owner].NftIDs[i]; } return Token_list; } function ownerTokenId(uint256 tokenId) external view returns (address){ return _stakingNFTs[tokenId].owner; } function onERC721Received(address,address,uint256,bytes memory) public view returns (bytes4) { return this.onERC721Received.selector; } function isWhiteContract(address account) public view returns (bool) { if(!account.isContract()) return true; return _Is_WhiteContractArr[account]; } function getWhiteAccountNum() public view returns (uint256){ return _WhiteContractArr.length; } function getWhiteAccountIth(uint256 ith) public view returns (address WhiteAddress){ require(ith <_WhiteContractArr.length, "ForthBox NFT DeFi: no ith White Adress"); return _WhiteContractArr[ith]; } function getParameters(address account) public view returns (uint256[] memory){ uint256[] memory paraList = new uint256[](uint256(5)); paraList[0]=totalRewardAlready; paraList[1]=basicDailyReward; paraList[2]=_totalSupply; paraList[3]=_balances[account]; paraList[4]= earned(account); return paraList; } //---write---// function stakes(uint256[] memory tokenIds) public nonReentrant updateReward(_msgSender()){ require(tokenIds.length<=100, "ForthBox NFT DeFi: num exceed 100!"); require(tokenIds.length>0, "ForthBox NFT DeFi: num 0!"); require(isWhiteContract(_msgSender()), "ForthBox NFT DeFi: Contract not in white list!"); for(uint256 i=0; i<tokenIds.length; ++i) { _stake(tokenIds[i]); } } function stake(uint256 tokenId) public nonReentrant updateReward(_msgSender()){ require(isWhiteContract(_msgSender()), "ForthBox NFT DeFi: Contract not in white list!"); _stake(tokenId); } function _stake(uint256 tokenId) internal { require(tokenId >= 0, "Cannot stake ID = 0"); uint256 amount = stakingToken.getHashrateByTokenId(tokenId); require(amount > 0, "Cannot stake 0"); stakingToken.safeTransferFrom(_msgSender(), address(this), tokenId); _balances[_msgSender()] = _balances[_msgSender()].add(amount); _totalSupply = _totalSupply.add(amount); _stakingNFTs[tokenId].value = amount; _stakingNFTs[tokenId].owner = _msgSender(); _OwnerNFTs[_msgSender()].NftIDs.push(tokenId); totalStakeTokens = totalStakeTokens + 1; emit Staked(_msgSender(), tokenId); } function stakeFresh(address ownerAdrr,uint256 tokenId) external nonReentrant updateReward(ownerAdrr){ require(ownerAdrr == _stakingNFTs[tokenId].owner , "ForthBox NFT DeFi: 1 Cannot Fresh not own id"); require(isWhiteContract(_msgSender()), "ForthBox NFT DeFi: Contract not in white list!"); if(address(_msgSender())!=address(stakingToken)){ require(_msgSender() == ownerAdrr , "ForthBox NFT DeFi: 2 Cannot Fresh not own id"); } uint256 amount = stakingToken.getHashrateByTokenId(tokenId); require(amount > _stakingNFTs[tokenId].value, "ForthBox NFT DeFi: need token hashrate > old Hashrate "); _balances[ownerAdrr] = _balances[ownerAdrr].add(amount.sub(_stakingNFTs[tokenId].value)); _totalSupply = _totalSupply.add(amount.sub(_stakingNFTs[tokenId].value)); _stakingNFTs[tokenId].value = amount; addFeedReward(ownerAdrr); emit StakeFresh(_msgSender(), tokenId); } function withdraw(uint256 tokenId) public nonReentrant updateReward(_msgSender()){ require(isWhiteContract(_msgSender()), "ForthBox NFT DeFi: Contract not in white list!"); _withdrawDel(tokenId); emit Withdrawn(_msgSender(), tokenId); } function _withdraw(uint256 tokenId) internal{ _totalSupply = _totalSupply.sub(_stakingNFTs[tokenId].value); _balances[_msgSender()] = _balances[_msgSender()].sub(_stakingNFTs[tokenId].value); stakingToken.safeTransferFrom(address(this),_msgSender(), tokenId); totalStakeTokens = totalStakeTokens.sub(1); } function _withdrawDel(uint256 tokenId) internal { require(_msgSender() == _stakingNFTs[tokenId].owner , "ForthBox NFT DeFi: Cannot withdraw not own id"); _withdraw(tokenId); for (uint256 i = 0; i < _OwnerNFTs[_msgSender()].NftIDs.length; i++){ if (_OwnerNFTs[_msgSender()].NftIDs[i] == tokenId){ _OwnerNFTs[_msgSender()].NftIDs[i] = _OwnerNFTs[_msgSender()].NftIDs[_OwnerNFTs[_msgSender()].NftIDs.length - 1]; _OwnerNFTs[_msgSender()].NftIDs.pop(); break; } } delete _stakingNFTs[tokenId]; } function getReward() public nonReentrant updateReward(_msgSender()){ require(isWhiteContract(_msgSender()), "ForthBox NFT DeFi: Contract not in white list!"); uint256 tFeedReward = getFeedReward_All(_msgSender()); uint256 reward = rewards[_msgSender()].add(tFeedReward); require(reward > 0, "ForthBox NFT DeFi: reward zero!"); if (tFeedReward > 0){ freshFeedReward(_msgSender()); } if (reward > 0){ rewards[_msgSender()] = 0; rewardsToken.safeTransfer(_msgSender(), reward); totalRewardAlready = totalRewardAlready.add(reward); emit RewardPaid(_msgSender(), reward); } } function exit() external nonReentrant updateReward(_msgSender()){ require(isWhiteContract(_msgSender()), "ForthBox NFT DeFi: Contract not in white list!"); _exit(_OwnerNFTs[_msgSender()].NftIDs.length); } function exits(uint256 num) external nonReentrant updateReward(_msgSender()){ require(isWhiteContract(_msgSender()), "ForthBox NFT DeFi: Contract not in white list!"); _exit(num); } function _exit(uint256 num) internal { require(num>0, "ForthBox NFT DeFi: num 0!"); if(num>=_OwnerNFTs[_msgSender()].NftIDs.length){ for (uint256 i = 0; i < _OwnerNFTs[_msgSender()].NftIDs.length; i++){ _withdraw(_OwnerNFTs[_msgSender()].NftIDs[i]); delete _stakingNFTs[_OwnerNFTs[_msgSender()].NftIDs[i]]; } delete _OwnerNFTs[_msgSender()]; } else{ uint256 LastNum = _OwnerNFTs[_msgSender()].NftIDs.length; for (uint256 i = 0; i < num; i++){ _withdraw(_OwnerNFTs[_msgSender()].NftIDs[LastNum-1-i]); delete _stakingNFTs[_OwnerNFTs[_msgSender()].NftIDs[LastNum-1-i]]; } for (uint256 i = 0; i < num; i++){ _OwnerNFTs[_msgSender()].NftIDs.pop(); } } uint256 tFeedReward = getFeedReward_All(_msgSender()); uint256 reward = rewards[_msgSender()].add(tFeedReward); if (tFeedReward > 0){ freshFeedReward(_msgSender()); } if (reward > 0){ rewards[_msgSender()] = 0; rewardsToken.safeTransfer(_msgSender(), reward); totalRewardAlready = totalRewardAlready.add(reward); } emit Exit(_msgSender()); } modifier updateReward(address account){ rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)){ rewards[account] = earned_Stake(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function addFeedReward(address account) internal { if(!bFeedReward) return; uint256 feedReward=stakingToken.feedFBXOnlyPrice(); uint256 dtReward = getFeedReward_dt(account); feedRewardArr[account].sum = feedRewardArr[account].sum.sub(dtReward).add(feedReward); feedRewardArr[account].alreadyReward = feedRewardArr[account].alreadyReward.add(dtReward); feedRewardArr[account].startTime = block.timestamp; return; } function freshFeedReward(address account) internal { uint256 dtReward = getFeedReward_dt(account); feedRewardArr[account].sum = feedRewardArr[account].sum.sub(dtReward); feedRewardArr[account].alreadyReward = 0; feedRewardArr[account].startTime = block.timestamp; return; } //---write onlyOwner---// function setTokens(address _rewardsToken,address _stakingToken,uint256 _rewardsDuration) external onlyOwner { rewardsToken = IERC20(_rewardsToken); stakingToken = IFBX_NFT_Token(_stakingToken); rewardsDuration = _rewardsDuration; } 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); } totalReward = totalReward.add(reward); uint256 balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "ForthBox NFT DeFi:Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } function setBasicDailyReward (uint256 newBasicDailyReward) onlyOwner public{ basicDailyReward = newBasicDailyReward ; } function setFeedReward (bool tFeedReward) onlyOwner public{ bFeedReward = tFeedReward; } function addWhiteAccount(address account) external onlyOwner{ require(!_Is_WhiteContractArr[account], "ForthBox NFT DeFi:Account is already White list"); require(account.isContract(), "ForthBox NFT DeFi: not Contract Adress"); _Is_WhiteContractArr[account] = true; _WhiteContractArr.push(account); } function removeWhiteAccount(address account) external onlyOwner{ require(_Is_WhiteContractArr[account], "ForthBox NFT DeFi:Account is already out White list"); for (uint256 i = 0; i < _WhiteContractArr.length; i++){ if (_WhiteContractArr[i] == account){ _WhiteContractArr[i] = _WhiteContractArr[_WhiteContractArr.length - 1]; _WhiteContractArr.pop(); _Is_WhiteContractArr[account] = false; break; } } } }
---write onlyOwner---
function setTokens(address _rewardsToken,address _stakingToken,uint256 _rewardsDuration) external onlyOwner { rewardsToken = IERC20(_rewardsToken); stakingToken = IFBX_NFT_Token(_stakingToken); rewardsDuration = _rewardsDuration; }
7,226,884
./partial_match/1/0xdc1D5B5B1aEEe8a90cdcAE38aa09C7582ECa8007/sources/MiningPool.sol
View function to see pending ADAMs on frontend.
function pendingAdam(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAdamPerShare = pool.accAdamPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 adamReward = multiplier.mul(adamPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAdamPerShare = accAdamPerShare.add(adamReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAdamPerShare).div(1e12).sub(user.rewardAdamDebt).mul(USER_SHARE_PCT).div(10000); }
4,108,240
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import './Proxy.sol'; import './OwnedUpgradeabilityStorage.sol'; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() override public view returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return proxyTypeId Proxy type, 2 for forwarding proxy */ function proxyType() override public pure returns (uint256 proxyTypeId) { return 2; } /** * @dev Upgrades the implementation address * @param newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address newImplementation) internal { require(_implementation != newImplementation, "Proxy already uses this implementation"); _implementation = newImplementation; emit Upgraded(newImplementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner(), "Only the proxy owner can call this method"); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0), "New owner cannot be the null address"); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param newImplementation representing the address of the new implementation to be set. */ function upgradeTo(address newImplementation) public onlyProxyOwner { _upgradeTo(newImplementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param newImplementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address newImplementation, bytes memory data) payable public onlyProxyOwner { upgradeTo(newImplementation); (bool success,) = address(this).delegatecall(data); require(success, "Call failed after proxy upgrade"); } }
Allows the upgradeability owner to upgrade the current implementation of the proxy and delegatecall the new implementation for initialization. newImplementation representing the address of the new implementation to be set. data represents the msg.data to bet sent in the low level call. This parameter may include the function signature of the implementation to be called with the needed payload/
function upgradeToAndCall(address newImplementation, bytes memory data) payable public onlyProxyOwner { upgradeTo(newImplementation); (bool success,) = address(this).delegatecall(data); require(success, "Call failed after proxy upgrade"); }
1,020,546
./partial_match/1/0x569Ff47E8DB142F52feFC82A9c41929fB3d49d4E/sources/ETHBridge.sol
Celer Network Bridge
interface IBridge { function sendNative( address _receiver, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage ) external payable; function transfers( bytes32 transferId ) external view returns (bool); pragma solidity ^0.8.9; }
15,467,571
pragma solidity ^0.4.23; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Autonomy is Ownable { address public congress; bool init = false; modifier onlyCongress() { require(msg.sender == congress); _; } /** * @dev initialize a Congress contract address for this token * * @param _congress address the congress contract address */ function initialCongress(address _congress) onlyOwner public { require(!init); require(_congress != address(0)); congress = _congress; init = true; } /** * @dev set a Congress contract address for this token * must change this address by the last congress contract * * @param _congress address the congress contract address */ function changeCongress(address _congress) onlyCongress public { require(_congress != address(0)); congress = _congress; } } contract withdrawable is Ownable { event ReceiveEther(address _from, uint256 _value); event WithdrawEther(address _to, uint256 _value); event WithdrawToken(address _token, address _to, uint256 _value); /** * @dev recording receiving ether from msn.sender */ function () payable public { emit ReceiveEther(msg.sender, msg.value); } /** * @dev withdraw,send ether to target * @param _to is where the ether will be sent to * _amount is the number of the ether */ function withdraw(address _to, uint _amount) public onlyOwner returns (bool) { require(_to != address(0)); _to.transfer(_amount); emit WithdrawEther(_to, _amount); return true; } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _to is where the tokens will be sent to * _value is the number of the token */ function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_token != address(0)); ERC20 tk = ERC20(_token); tk.transfer(_to, _value); emit WithdrawToken(_token, _to, _value); return true; } /** * @dev receive approval from an ERC20 token contract, and then gain the tokens, * then take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ // function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { // require(_token != address(0)); // require(_from != address(0)); // ERC20 tk = ERC20(_token); // require(tk.transferFrom(_from, this, _value)); // emit ReceiveDeposit(_from, _value, _token, _extraData); // } } contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract TokenDestructible is Ownable { function TokenDestructible() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } 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 { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract OwnerContract is Claimable { Claimable public ownedContract; address internal origOwner; /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function bindContract(address _contract) onlyOwner public returns (bool) { require(_contract != address(0)); ownedContract = Claimable(_contract); origOwner = ownedContract.owner(); // take ownership of the owned contract ownedContract.claimOwnership(); return true; } /** * @dev change the owner of the contract from this contract address to the original one. * */ function transferOwnershipBack() onlyOwner public { ownedContract.transferOwnership(origOwner); ownedContract = Claimable(address(0)); origOwner = address(0); } /** * @dev change the owner of the contract from this contract address to another one. * * @param _nextOwner the contract address that will be next Owner of the original Contract */ function changeOwnershipto(address _nextOwner) onlyOwner public { ownedContract.transferOwnership(_nextOwner); ownedContract = Claimable(address(0)); origOwner = address(0); } } contract DepositWithdraw is Claimable, withdrawable { using SafeMath for uint256; /** * transaction record */ struct TransferRecord { uint256 timeStamp; address account; uint256 value; } /** * accumulated transferring amount record */ struct accumulatedRecord { uint256 mul; uint256 count; uint256 value; } TransferRecord[] deposRecs; // record all the deposit tx data TransferRecord[] withdrRecs; // record all the withdraw tx data accumulatedRecord dayWithdrawRec; // accumulated amount record for one day accumulatedRecord monthWithdrawRec; // accumulated amount record for one month address wallet; // the binded withdraw address event ReceiveDeposit(address _from, uint256 _value, address _token, bytes _extraData); /** * @dev constructor of the DepositWithdraw contract * @param _wallet the binded wallet address to this depositwithdraw contract */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } /** * @dev set the default wallet address * @param _wallet the default wallet address binded to this deposit contract */ function setWithdrawWallet(address _wallet) onlyOwner public returns (bool) { require(_wallet != address(0)); wallet = _wallet; return true; } /** * @dev util function to change bytes data to bytes32 data * @param _data the bytes data to be converted */ function bytesToBytes32(bytes _data) public pure returns (bytes32 result) { assembly { result := mload(add(_data, 32)) } } /** * @dev receive approval from an ERC20 token contract, take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) onlyOwner public { require(_token != address(0)); require(_from != address(0)); ERC20 tk = ERC20(_token); require(tk.transferFrom(_from, this, _value)); bytes32 timestamp = bytesToBytes32(_extraData); deposRecs.push(TransferRecord(uint256(timestamp), _from, _value)); emit ReceiveDeposit(_from, _value, _token, _extraData); } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timstamp of the withdraw time * @param _to is where the tokens will be sent to * _value is the number of the token * _fee is the amount of the transferring costs * _tokenReturn is the address that return back the tokens of the _fee */ function withdrawToken(address _token, address _params, uint256 _time, address _to, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner returns (bool) { require(_to != address(0)); require(_token != address(0)); require(_value > _fee); // require(_tokenReturn != address(0)); DRCWalletMgrParams params = DRCWalletMgrParams(_params); require(_value <= params.singleWithdrawMax()); require(_value >= params.singleWithdrawMin()); uint256 daysCount = _time.div(86400); // one day of seconds if (daysCount <= dayWithdrawRec.mul) { dayWithdrawRec.count = dayWithdrawRec.count.add(1); dayWithdrawRec.value = dayWithdrawRec.value.add(_value); require(dayWithdrawRec.count <= params.dayWithdrawCount()); require(dayWithdrawRec.value <= params.dayWithdraw()); } else { dayWithdrawRec.mul = daysCount; dayWithdrawRec.count = 1; dayWithdrawRec.value = _value; } uint256 monthsCount = _time.div(86400 * 30); if (monthsCount <= monthWithdrawRec.mul) { monthWithdrawRec.count = monthWithdrawRec.count.add(1); monthWithdrawRec.value = monthWithdrawRec.value.add(_value); require(monthWithdrawRec.value <= params.monthWithdraw()); } else { monthWithdrawRec.mul = monthsCount; monthWithdrawRec.count = 1; monthWithdrawRec.value = _value; } ERC20 tk = ERC20(_token); uint256 realAmount = _value.sub(_fee); require(tk.transfer(_to, realAmount)); if (_tokenReturn != address(0) && _fee > 0) { require(tk.transfer(_tokenReturn, _fee)); } withdrRecs.push(TransferRecord(_time, _to, realAmount)); emit WithdrawToken(_token, _to, realAmount); return true; } /** * @dev withdraw tokens, send tokens to target default wallet * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timestamp occur the withdraw record * @param _value is the number of the token * _fee is the amount of the transferring costs * —tokenReturn is the address that return back the tokens of the _fee */ function withdrawTokenToDefault(address _token, address _params, uint256 _time, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner returns (bool) { return withdrawToken(_token, _params, _time, wallet, _value, _fee, _tokenReturn); } /** * @dev get the Deposit records number * */ function getDepositNum() public view returns (uint256) { return deposRecs.length; } /** * @dev get the one of the Deposit records * * @param _ind the deposit record index */ function getOneDepositRec(uint256 _ind) public view returns (uint256, address, uint256) { require(_ind < deposRecs.length); return (deposRecs[_ind].timeStamp, deposRecs[_ind].account, deposRecs[_ind].value); } /** * @dev get the withdraw records number * */ function getWithdrawNum() public view returns (uint256) { return withdrRecs.length; } /** * @dev get the one of the withdraw records * * @param _ind the withdraw record index */ function getOneWithdrawRec(uint256 _ind) public view returns (uint256, address, uint256) { require(_ind < withdrRecs.length); return (withdrRecs[_ind].timeStamp, withdrRecs[_ind].account, withdrRecs[_ind].value); } } contract DRCWalletManager is OwnerContract, withdrawable, Destructible, TokenDestructible { using SafeMath for uint256; /** * withdraw wallet description */ struct WithdrawWallet { bytes32 name; address walletAddr; } /** * Deposit data storage */ struct DepositRepository { // uint256 balance; uint256 frozen; WithdrawWallet[] withdrawWallets; // mapping (bytes32 => address) withdrawWallets; } mapping (address => DepositRepository) depositRepos; mapping (address => address) walletDeposits; mapping (address => bool) public frozenDeposits; ERC20 public tk; // the token will be managed DRCWalletMgrParams params; // the parameters that the management needs event CreateDepositAddress(address indexed _wallet, address _deposit); event FrozenTokens(address indexed _deposit, uint256 _value); event ChangeDefaultWallet(address indexed _oldWallet, address _newWallet); /** * @dev withdraw tokens, send tokens to target default wallet * * @param _token the token address that will be withdraw * @param _walletParams the wallet management parameters */ function bindToken(address _token, address _walletParams) onlyOwner public returns (bool) { require(_token != address(0)); require(_walletParams != address(0)); tk = ERC20(_token); params = DRCWalletMgrParams(_walletParams); return true; } /** * @dev create deposit contract address for the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function createDepositContract(address _wallet) onlyOwner public returns (address) { require(_wallet != address(0)); DepositWithdraw deposWithdr = new DepositWithdraw(_wallet); // new contract for deposit address _deposit = address(deposWithdr); walletDeposits[_wallet] = _deposit; WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; withdrawWalletList.push(WithdrawWallet("default wallet", _wallet)); // depositRepos[_deposit].balance = 0; depositRepos[_deposit].frozen = 0; emit CreateDepositAddress(_wallet, address(deposWithdr)); return deposWithdr; } /** * @dev get deposit contract address by using the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function getDepositAddress(address _wallet) onlyOwner public view returns (address) { require(_wallet != address(0)); address deposit = walletDeposits[_wallet]; return deposit; } /** * @dev get deposit balance and frozen amount by using the deposit address * * @param _deposit the deposit contract address */ function getDepositInfo(address _deposit) onlyOwner public view returns (uint256, uint256) { require(_deposit != address(0)); uint256 _balance = tk.balanceOf(_deposit); uint256 frozenAmount = depositRepos[_deposit].frozen; // depositRepos[_deposit].balance = _balance; return (_balance, frozenAmount); } /** * @dev get the number of withdraw wallet addresses bindig to the deposit contract address * * @param _deposit the deposit contract address */ function getDepositWithdrawCount(address _deposit) onlyOwner public view returns (uint) { require(_deposit != address(0)); WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; uint len = withdrawWalletList.length; return len; } /** * @dev get the withdraw wallet addresses list binding to the deposit contract address * * @param _deposit the deposit contract address * @param _indices the array of indices of the withdraw wallets */ function getDepositWithdrawList(address _deposit, uint[] _indices) onlyOwner public view returns (bytes32[], address[]) { require(_indices.length != 0); bytes32[] memory names = new bytes32[](_indices.length); address[] memory wallets = new address[](_indices.length); for (uint i = 0; i < _indices.length; i = i.add(1)) { WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[_indices[i]]; names[i] = wallet.name; wallets[i] = wallet.walletAddr; } return (names, wallets); } /** * @dev change the default withdraw wallet address binding to the deposit contract address * * @param _oldWallet the previous default withdraw wallet * @param _newWallet the new default withdraw wallet */ function changeDefaultWithdraw(address _oldWallet, address _newWallet) onlyOwner public returns (bool) { require(_newWallet != address(0)); address deposit = walletDeposits[_oldWallet]; DepositWithdraw deposWithdr = DepositWithdraw(deposit); require(deposWithdr.setWithdrawWallet(_newWallet)); WithdrawWallet[] storage withdrawWalletList = depositRepos[deposit].withdrawWallets; withdrawWalletList[0].walletAddr = _newWallet; emit ChangeDefaultWallet(_oldWallet, _newWallet); return true; } /** * @dev freeze the tokens in the deposit address * * @param _deposit the deposit address * @param _value the amount of tokens need to be frozen */ function freezeTokens(address _deposit, uint256 _value) onlyOwner public returns (bool) { require(_deposit != address(0)); frozenDeposits[_deposit] = true; depositRepos[_deposit].frozen = _value; emit FrozenTokens(_deposit, _value); return true; } /** * @dev withdraw the tokens from the deposit address with charge fee * * @param _deposit the deposit address * @param _time the timestamp the withdraw occurs * @param _value the amount of tokens need to be frozen */ function withdrawWithFee(address _deposit, uint256 _time, uint256 _value) onlyOwner public returns (bool) { require(_deposit != address(0)); uint256 _balance = tk.balanceOf(_deposit); require(_value <= _balance); // depositRepos[_deposit].balance = _balance; uint256 frozenAmount = depositRepos[_deposit].frozen; require(_value <= _balance.sub(frozenAmount)); DepositWithdraw deposWithdr = DepositWithdraw(_deposit); return (deposWithdr.withdrawTokenToDefault(address(tk), address(params), _time, _value, params.chargeFee(), params.chargeFeePool())); } /** * @dev check if the wallet name is not matching the expected wallet address * * @param _deposit the deposit address * @param _name the withdraw wallet name * @param _to the withdraw wallet address */ function checkWithdrawAddress(address _deposit, bytes32 _name, address _to) public view returns (bool, bool) { uint len = depositRepos[_deposit].withdrawWallets.length; for (uint i = 0; i < len; i = i.add(1)) { WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[i]; if (_name == wallet.name) { return(true, (_to == wallet.walletAddr)); } } return (false, true); } /** * @dev withdraw tokens, send tokens to target withdraw wallet * * @param _deposit the deposit address that will be withdraw from * @param _time the timestamp occur the withdraw record * @param _name the withdraw address alias name to verify * @param _to the address the token will be transfer to * @param _value the token transferred value * @param _check if we will check the value is valid or meet the limit condition */ function withdrawWithFee(address _deposit, uint256 _time, bytes32 _name, address _to, uint256 _value, bool _check) onlyOwner public returns (bool) { require(_deposit != address(0)); require(_to != address(0)); uint256 _balance = tk.balanceOf(_deposit); if (_check) { require(_value <= _balance); } uint256 available = _balance.sub(depositRepos[_deposit].frozen); if (_check) { require(_value <= available); } bool exist; bool correct; WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; (exist, correct) = checkWithdrawAddress(_deposit, _name, _to); if(!exist) { withdrawWalletList.push(WithdrawWallet(_name, _to)); } else if(!correct) { return false; } if (!_check && _value > available) { tk.transfer(_deposit, _value.sub(available)); // _value = _value.sub(available); } DepositWithdraw deposWithdr = DepositWithdraw(_deposit); return (deposWithdr.withdrawToken(address(tk), address(params), _time, _to, _value, params.chargeFee(), params.chargeFeePool())); } } contract DRCWalletMgrParams is Claimable, Autonomy, Destructible { uint256 public singleWithdrawMin; // min value of single withdraw uint256 public singleWithdrawMax; // Max value of single withdraw uint256 public dayWithdraw; // Max value of one day of withdraw uint256 public monthWithdraw; // Max value of one month of withdraw uint256 public dayWithdrawCount; // Max number of withdraw counting uint256 public chargeFee; // the charge fee for withdraw address public chargeFeePool; // the address that will get the returned charge fees. function initialSingleWithdrawMax(uint256 _value) onlyOwner public { require(!init); singleWithdrawMax = _value; } function initialSingleWithdrawMin(uint256 _value) onlyOwner public { require(!init); singleWithdrawMin = _value; } function initialDayWithdraw(uint256 _value) onlyOwner public { require(!init); dayWithdraw = _value; } function initialDayWithdrawCount(uint256 _count) onlyOwner public { require(!init); dayWithdrawCount = _count; } function initialMonthWithdraw(uint256 _value) onlyOwner public { require(!init); monthWithdraw = _value; } function initialChargeFee(uint256 _value) onlyOwner public { require(!init); chargeFee = _value; } function initialChargeFeePool(address _pool) onlyOwner public { require(!init); chargeFeePool = _pool; } function setSingleWithdrawMax(uint256 _value) onlyCongress public { singleWithdrawMax = _value; } function setSingleWithdrawMin(uint256 _value) onlyCongress public { singleWithdrawMin = _value; } function setDayWithdraw(uint256 _value) onlyCongress public { dayWithdraw = _value; } function setDayWithdrawCount(uint256 _count) onlyCongress public { dayWithdrawCount = _count; } function setMonthWithdraw(uint256 _value) onlyCongress public { monthWithdraw = _value; } function setChargeFee(uint256 _value) onlyCongress public { chargeFee = _value; } function setChargeFeePool(address _pool) onlyCongress public { chargeFeePool = _pool; } } 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 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); }
get deposit balance and frozen amount by using the deposit address _deposit the deposit contract address/ depositRepos[_deposit].balance = _balance;
function getDepositInfo(address _deposit) onlyOwner public view returns (uint256, uint256) { require(_deposit != address(0)); uint256 _balance = tk.balanceOf(_deposit); uint256 frozenAmount = depositRepos[_deposit].frozen; return (_balance, frozenAmount); }
9,845,240
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.0; import { WrappedCoveredPrincipalToken, EnumerableSet } from "./WrappedCoveredPrincipalToken.sol"; /// @author Element Finance /// @title WrappedCoveredPrincipalTokenFactory contract WrappedCoveredPrincipalTokenFactory { using EnumerableSet for EnumerableSet.AddressSet; // Enumerable list of wrapped tokens that get created from the factory. EnumerableSet.AddressSet private _WrappedCoveredPrincipalTokens; // Tranche factory address for Tranche contract address derivation address internal immutable _trancheFactory; // Tranche bytecode hash for Tranche contract address derivation. // This is constant as long as Tranche does not implement non-constant constructor arguments. bytes32 internal immutable _trancheBytecodeHash; // Emitted when new wrapped principal token get created. event WrappedCoveredPrincipalTokenCreated( address indexed _baseToken, address indexed _owner, address _wcPrincipalToken ); /// @notice Initializing the owner of the contract. constructor(address __trancheFactory, bytes32 __trancheBytecodeHash) { _trancheFactory = __trancheFactory; _trancheBytecodeHash = __trancheBytecodeHash; } /// @notice Allow the owner to create the new wrapped token. /// @param _baseToken Address of the base token / underlying token that is used to buy the wrapped positions. /// @param _owner Address of the owner of wrapped futures. /// @return address of wrapped futures token. function create(address _baseToken, address _owner) external returns (address) { // Validate the given params _zeroAddressCheck(_owner); _zeroAddressCheck(_baseToken); address wcPrincipal = address( new WrappedCoveredPrincipalToken( _baseToken, _owner, _trancheFactory, _trancheBytecodeHash ) ); _WrappedCoveredPrincipalTokens.add(wcPrincipal); emit WrappedCoveredPrincipalTokenCreated( _baseToken, _owner, wcPrincipal ); return wcPrincipal; } /// @notice Returns the list of wrapped tokens that are whitelisted with the contract. /// Order is not maintained. /// @return Array of addresses. function allWrappedCoveredPrincipalTokens() public view returns (address[] memory) { return _WrappedCoveredPrincipalTokens.values(); } /// @notice Sanity check for the zero address check. function _zeroAddressCheck(address _target) internal pure { require(_target != address(0), "WFPF:ZERO_ADDRESS"); } }
Sanity check for the zero address check.
function _zeroAddressCheck(address _target) internal pure { require(_target != address(0), "WFPF:ZERO_ADDRESS"); }
14,105,354
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
Reads the bytes32 at `mPtr` in memory.
function readBytes32( MemoryPointer mPtr ) internal pure returns (bytes32 value) { assembly { value := mload(mPtr) } }
3,218,648
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract SimpleStorage { // will be initialized to 0 uint256 public favoriteNumber; uint256 public extra = 44; struct People { uint256 favNumber; string name; } People public person = People({favNumber:2, name:"Matt"}); People[] public people; mapping(string => uint256) public nameToFaboriteNumber; // 'memory' or 'storage' function addPerson(string memory _name, uint256 _favNumber) public { people.push(People({favNumber: _favNumber, name: _name})); nameToFaboriteNumber[_name] = _favNumber; } function store(uint256 _favoriteNumber) public { favoriteNumber = _favoriteNumber; uint256 test = 4; } // 'view' or 'pure' doesn't cost gas because it is read operation and doesn't create a new transaction. // view reads, pure performs operation function retrieve() public view returns(uint256) { return favoriteNumber; } // pure can't even access favoriteNumber, because then it will also read the state and require 'view' function calculate(uint256 number) public pure { number + number; } }
'memory' or 'storage'
function addPerson(string memory _name, uint256 _favNumber) public { nameToFaboriteNumber[_name] = _favNumber; }
12,707,754
./full_match/5/0xE803063793d3798349679079aeC82BD7bB0F4589/sources/contract-7485c339b2.sol
This function uses a set amount of gas to process dividends for as many wallets as it can gas The amount of gas to use for processing dividends return numProcessed The number of wallets processed return numClaims The number of actual claims sent return lastIndex The index of the last wallet processed
function process(uint256 gas) public onlyRole(TOKEN_ADMIN_ROLE) returns ( uint256 numProcessed, uint256 numClaims, uint256 lastIndex ) { uint256 numHolders = dividendHolders.keys.length; if (numHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= dividendHolders.keys.length) { _lastProcessedIndex = 0; } address account = dividendHolders.keys[_lastProcessedIndex]; if ( canAutoClaim(claimTimes[account]) && _processAccount(payable(account), true) ) { claims++; } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed += gasLeft - newGasLeft; } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, _lastProcessedIndex); }
7,088,057
pragma solidity ^0.4.13; //date 1500114129 by Ournet International2022649 contract tokenGAT { uint256 public totalContribution = 0; uint256 public totalBonusTokensIssued = 0; uint256 public totalSupply = 0; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); //events for logging event LogTransaction(address indexed _addres, uint256 value); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* ERC 20 token this funtion are also call when somebody or contract want transfer, send, u operate wiht our tokens*/ contract StandarTokentokenGAT is tokenGAT{ mapping (address => uint256) balances; //asociative array for associate address and its balance like a hashmapp in java mapping (address => uint256 ) weirecives; //asociative array for associate address and its balance like a hashmapp in java mapping (address => mapping (address => uint256)) allowed; // this store addres that are allowed for operate in this contract function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success) { if(msg.data.length < (2 * 32) + 4) { revert();} // mitigates the ERC20 short address attack if (balances[msg.sender] >= _value && _value >= 0){ balances[msg.sender] -= _value; //substract balance from user that is transfering (who deploy or who executed it) balances[_to] += _value; //add balance from user that is transfering (who deploy or who executed it) Transfer(msg.sender, _to, _value); //login return true; }else return false; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if(msg.data.length < (3 * 32) + 4) { revert(); } // mitigates the ERC20 short address attack if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value >= 0){ //add balance to destinate address balances[_to] += _value; //substract balance from source address balances[_from] -= _value; allowed[_from][msg.sender] -= _value; //loggin Transfer(_from, _to, _value); return true; } else return false; } //put the addres in allowed mapping function approve(address _spender, uint256 _value) returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract TokenICOGAT is StandarTokentokenGAT{ address owner = msg.sender; //Token Metadata function name() constant returns (string) { return "General Advertising Token"; } function symbol() constant returns (string) { return "GAT"; } uint256 public constant decimals = 18; //ICO Parameters bool public purchasingAllowed = false; address public ethFoundDeposit; // deposit address for ETH for OurNet International address public gatFoundDeposit; // deposit address for Brave International use and OurNet User Fund uint public deadline; //epoch date to end of crowsale uint public startline; //when crowsale start uint public refundDeadLine; // peiorode avaible for get refound uint public transactionCounter;//counter for calcucalate bonus uint public etherReceived; // Number of Ether received uint256 public constant gatFund = 250 * (10**6) * 10**decimals; // 250m GAT reserved for OurNet Intl use, early adopters incentive and ournNet employees team uint256 public constant tokenExchangeRate = 9000; // 9000 GAT tokens per 1 ETH uint256 public constant tokenCreationCap = 1000 * (10**6) * 10**decimals; //total of tokens issued uint256 public constant tokenSellCap = 750 * (10**6) * 10**decimals; //maximun of gat tokens for sell uint256 public constant tokenSaleMin = 17 * (10**6) * 10**decimals; //minimun goal //constructor or contract function TokenICOGAT(){ startline = now; deadline = startline + 45 * 1 days; refundDeadLine = deadline + 30 days; ethFoundDeposit = owner; gatFoundDeposit = owner; balances[gatFoundDeposit] = gatFund; //deposit fondos for ourNet international LogTransaction(gatFoundDeposit,gatFund); //login transaction } function bonusCalculate(uint256 amount) internal returns(uint256){ uint256 amounttmp = 0; if (transactionCounter > 0 && transactionCounter <= 1000){ return amount / 2 ; // bonus 50% } if (transactionCounter > 1000 && transactionCounter <= 2000){ return amount / 5 ; // bonus 20% } if (transactionCounter > 2000 && transactionCounter <= 3000){ return amount / 10; // bonus 10% } if (transactionCounter > 3000 && transactionCounter <= 5000){ return amount / 20; // bonus 5% } return amounttmp; } function enablePurchasing() { if (msg.sender != owner) { revert(); } if(purchasingAllowed) {revert();} purchasingAllowed = true; } function disablePurchasing() { if (msg.sender != owner) { revert(); } if(!purchasingAllowed) {revert();} purchasingAllowed = false; } function getStats() constant returns (uint256, uint256, uint256, bool) { return (totalContribution, totalSupply, totalBonusTokensIssued, purchasingAllowed); } // recive ethers funtion witout name is call every some body send ether function() payable { if (!purchasingAllowed) { revert(); } if ((tokenCreationCap - (totalSupply + gatFund)) <= 0) { revert();} if (msg.value == 0) { return; } transactionCounter +=1; totalContribution += msg.value; uint256 bonusGiven = bonusCalculate(msg.value); // Number of GAT sent to Ether contributors uint256 tokensIssued = (msg.value * tokenExchangeRate) + (bonusGiven * tokenExchangeRate); totalBonusTokensIssued += bonusGiven; totalSupply += tokensIssued; balances[msg.sender] += tokensIssued; weirecives[msg.sender] += msg.value; // it is import for calculate refund witout token bonus Transfer(address(this), msg.sender, tokensIssued); } // send excess of tokens when de ico end function sendSurplusTokens() { if (purchasingAllowed) { revert(); } if (msg.sender != owner) { revert();} uint256 excess = tokenCreationCap - (totalSupply + gatFund); if(excess <= 0){revert();} balances[gatFoundDeposit] += excess; Transfer(address(this), gatFoundDeposit, excess); } function withdrawEtherHomeExternal() external{//Regarding security issues the first option is save ether in a online wallet, but if some bad happens, we will use local wallet as contingency plan if(purchasingAllowed){revert();} if (msg.sender != owner) { revert();} ethFoundDeposit.transfer(this.balance); //send ether home } function withdrawEtherHomeLocal(address _ethHome) external{ // continegency plan if(purchasingAllowed){revert();} if (msg.sender != owner) { revert();} _ethHome.transfer(this.balance); //send ether home } /* * When tokenSaleMin is not reach: * 1) donors call the "refund" function of the GATCrowdFundingToken contract */ function refund() public { if(purchasingAllowed){revert();} // only refund after ico end if(now >= refundDeadLine ){revert();} // only refund are available before ico end + 30 days if((totalSupply - totalBonusTokensIssued) >= tokenSaleMin){revert();} // if we sould enough, no refund allow if(msg.sender == ethFoundDeposit){revert();} // OurNet not entitled to a refund uint256 gatVal= balances[msg.sender]; // get balance of who is getting from balances mapping if(gatVal <=0) {revert();} //if dont have balnace sent no refund // balances[msg.sender] = 0;//since donor can hold the tokes as souvenir do not update balance of who is getting refund in gatcontract uint256 ethVal = weirecives[msg.sender]; //extract amount contribuited by sender without tokenbonus LogTransaction(msg.sender,ethVal);//loggin transaction msg.sender.transfer(ethVal);// send ether comeback totalContribution -= ethVal; weirecives[msg.sender] -= ethVal; // getrefound from weirecives } }
put the addres in allowed mapping mitigates the ERC20 spend/approval race condition
function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
1,797,820
pragma solidity 0.4.24; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Admin is Ownable { using SafeMath for uint256; struct Tier { uint256 amountInCenter; uint256 amountInOuter; uint256 priceInCenter; uint256 priceInOuter; uint256 soldInCenter; uint256 soldInOuter; bool filledInCenter; bool filledInOuter; } Tier[] public tiers; bool public halted; uint256 public logoPrice = 0; uint256 public logoId; address public platformWallet; uint256 public feeForFirstArtWorkChangeRequest = 0 ether; uint256 public feeForArtWorkChangeRequest = 0.2 ether; uint256 public minResalePercentage = 15; mapping(address => bool) public globalAdmins; mapping(address => bool) public admins; mapping(address => bool) public signers; event Halted(bool _halted); modifier onlyAdmin() { require(true == admins[msg.sender] || true == globalAdmins[msg.sender]); _; } modifier onlyGlobalAdmin() { require(true == globalAdmins[msg.sender]); _; } modifier notHalted() { require(halted == false); _; } function addGlobalAdmin(address _address) public onlyOwner() { globalAdmins[_address] = true; } function removeGlobalAdmin(address _address) public onlyOwner() { globalAdmins[_address] = false; } function addAdmin(address _address) public onlyGlobalAdmin() { admins[_address] = true; } function removeAdmin(address _address) public onlyGlobalAdmin() { admins[_address] = true; } function setSigner(address _address, bool status) public onlyGlobalAdmin() { signers[_address] = status; } function setLogoPrice(uint256 _price) public onlyGlobalAdmin() { logoPrice = _price; } function setFeeForFirstArtWorkChangeRequest(uint256 _fee) public onlyGlobalAdmin() { feeForFirstArtWorkChangeRequest = _fee; } function setFeeForArtWorkChangeRequest(uint256 _fee) public onlyGlobalAdmin() { feeForArtWorkChangeRequest = _fee; } /// @notice global Admin update tier data function setTierData( uint256 _index, uint256 _priceInCenter, uint256 _priceInOuter) public onlyGlobalAdmin() { Tier memory tier = tiers[_index]; tier.priceInCenter = _priceInCenter; tier.priceInOuter = _priceInOuter; tiers[_index] = tier; } function setMinResalePercentage(uint256 _minResalePercentage) public onlyGlobalAdmin() { minResalePercentage = _minResalePercentage; } function isAdmin(address _address) public view returns (bool isAdmin_) { return (true == admins[_address] || true == globalAdmins[_address]); } function setHalted(bool _halted) public onlyGlobalAdmin { halted = _halted; emit Halted(_halted); } function verify(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(abi.encodePacked(prefix, _hash)), _v, _r, _s); } function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } function setPlatformWallet(address _addresss) public onlyGlobalAdmin() { platformWallet = _addresss; } } contract BigIoAdSpace is Ownable { using SafeMath for uint256; /// @notice Token struct Token { uint256 id; uint256 x; // position X on map uint256 y; // position Y on map uint256 sizeA; uint256 sizeB; uint256 soldPrice; // price that user paid to buy token uint256 actualPrice; uint256 timesSold; // how many times token was sold uint256 timesUpdated; // how many times artwork has been changed by current owner uint256 soldAt; // when token was sold uint256 inner; uint256 outer; uint256 soldNearby; } struct MetaData { string meta; } struct InnerScope { uint256 x1; // left top uint256 y1; uint256 x2; // right top uint256 y2; uint256 x3; // left bottom uint256 y3; uint256 x4; // right bottom uint256 y4; } InnerScope public innerScope; /// @notice mapping for token URIs mapping(uint256 => MetaData) public metadata; /// @notice Mapping from token ID to owner mapping(uint256 => address) public tokenOwner; mapping(uint256 => mapping(uint256 => bool)) public neighbours; mapping(uint256 => uint256[]) public neighboursArea; /// @notice Here different from base class we store the token not an id /// Array with all token, used for enumeration Token[] public allMinedTokens; /// @notice Mapping from token id to position in the allMinedTokens array mapping(uint256 => uint256) public allTokensIndex; // store sold units and not-sold but generated units // mapping(uint256 => mapping(uint256 => bool)) public soldUnits; mapping(uint256 => mapping(uint256 => uint256)) public soldUnits; address public platform; event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event TokenPriceIncreased(uint256 _tokenId, uint256 _newPrice, uint256 _boughtTokenId, uint256 time); constructor () public { innerScope = InnerScope( 12, 11, // left top 67, 11, // right top 12, 34, // left bottom 67, 34 ); } modifier onlyPlatform() { require(msg.sender == platform); _; } modifier exists(uint256 _tokenId) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); _; } function setPlatform(address _platform) public onlyOwner() { platform = _platform; } function totalSupply() public view returns (uint256) { return allMinedTokens.length; } /// @notice Check whether token is minted function tokenExists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /// @notice Check whether exist Unit with same x any y coordinates /// and it was sold already /// in order to prevent over writing function unitExists(uint x, uint y) public view returns (bool) { return (soldUnits[x][y] != 0); } function getOwner(uint256 _tokenId) public view returns (address) { return tokenOwner[_tokenId]; } /// @return token metadata function getMetadata(uint256 _tokenId) public exists(_tokenId) view returns (string) { return metadata[_tokenId].meta; } /// @notice update metadata for token function setTokenMetadata(uint256 _tokenId, string meta) public onlyPlatform exists(_tokenId) { metadata[_tokenId] = MetaData(meta); } function increaseUpdateMetadataCounter(uint256 _tokenId) public onlyPlatform { allMinedTokens[allTokensIndex[_tokenId]].timesUpdated = allMinedTokens[allTokensIndex[_tokenId]].timesUpdated.add(1); } /// @notice remove metadata for token function removeTokenMetadata(uint256 _tokenId) public onlyPlatform exists(_tokenId) { delete metadata[_tokenId]; } // @return return the current price function getCurrentPriceForToken(uint256 _tokenId) public exists(_tokenId) view returns (uint256) { return allMinedTokens[allTokensIndex[_tokenId]].actualPrice; } /// @return tokenId, x, y, sizeA, sizeB, price, inner, outer function getTokenData(uint256 _tokenId) public exists(_tokenId) view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (_tokenId, token.x, token.y, token.sizeA, token.sizeB, token.actualPrice, token.soldPrice, token.inner, token.outer); } function getTokenSoldPrice(uint256 _tokenId) public exists(_tokenId) view returns (uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return token.soldPrice; } function getTokenUpdatedCounter(uint256 _tokenId) public exists(_tokenId) view returns (uint256) { return allMinedTokens[allTokensIndex[_tokenId]].timesUpdated; } // @return return token sizes function getTokenSizes(uint256 _tokenId) public exists(_tokenId) view returns (uint256, uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (token.sizeA, token.sizeB); } // @return return token scopes function getTokenScope(uint256 _tokenId) public exists(_tokenId) view returns (bool, bool) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (token.inner > 0, token.outer > 0); } // @return return token scope counters function getTokenCounters(uint256 _tokenId) public exists(_tokenId) view returns (uint256, uint256, uint256, uint256) { Token memory token = allMinedTokens[allTokensIndex[_tokenId]]; return (token.inner, token.outer, token.timesSold, token.soldNearby); } /// @notice Mint new token, not sell new token /// BE sends: owner, x coordinate, y coordinate, price /// @param to new owner /// @param x coordinate /// @param y coordinate /// @param totalPrice calculated price for all units + % for siblings function mint( address to, uint x, uint y, uint sizeA, uint sizeB, uint256 totalPrice, uint256 actualPrice ) public onlyPlatform() returns (uint256) { // 1. require(to != address(0)); require(sizeA.mul(sizeB) <= 100); // 2. check area uint256 inner; uint256 total; (total, inner) = calculateCounters(x, y, sizeA, sizeB); // we avoid zero because we later compare against zero uint256 tokenId = (allMinedTokens.length).add(1); // @TODO: ACHTUNG - soldAt equals 0 during minting Token memory minted = Token(tokenId, x, y, sizeA, sizeB, totalPrice, actualPrice, 0, 0, 0, inner, total.sub(inner), 0); // 3. copy units and create siblings copyToAllUnits(x, y, sizeA, sizeB, tokenId); // 4. update state updateInternalState(minted, to); return tokenId; } function updateTokensState(uint256 _tokenId, uint256 newPrice) public onlyPlatform exists(_tokenId) { uint256 index = allTokensIndex[_tokenId]; allMinedTokens[index].timesSold += 1; allMinedTokens[index].timesUpdated = 0; allMinedTokens[index].soldNearby = 0; allMinedTokens[index].soldPrice = newPrice; allMinedTokens[index].actualPrice = newPrice; allMinedTokens[index].soldAt = now; } function updateOwner(uint256 _tokenId, address newOwner, address prevOwner) public onlyPlatform exists(_tokenId) { require(newOwner != address(0)); require(prevOwner != address(0)); require(prevOwner == tokenOwner[_tokenId]); // update data for new owner tokenOwner[_tokenId] = newOwner; } function inInnerScope(uint256 x, uint256 y) public view returns (bool) { // x should be between left top and right top corner // y should be between left top and left bottom corner if ((x >= innerScope.x1) && (x <= innerScope.x2) && (y >= innerScope.y1) && (y <= innerScope.y3)) { return true; } return false; } function calculateCounters(uint256 x, uint256 y, uint256 sizeA, uint256 sizeB) public view returns (uint256 total, uint256 inner) { uint256 upX = x.add(sizeA); uint256 upY = y.add(sizeB); // check for boundaries require(x >= 1); require(y >= 1); require(upX <= 79); require(upY <= 45); require(sizeA > 0); require(sizeB > 0); uint256 i; uint256 j; for (i = x; i < upX; i++) { for (j = y; j < upY; j++) { require(soldUnits[i][j] == 0); if (inInnerScope(i, j)) { inner = inner.add(1); } total = total.add(1); } } } function increasePriceForNeighbours(uint256 tokenId) public onlyPlatform { Token memory token = allMinedTokens[allTokensIndex[tokenId]]; uint256 upX = token.x.add(token.sizeA); uint256 upY = token.y.add(token.sizeB); uint256 i; uint256 j; uint256 k; uint256 _tokenId; if (neighboursArea[tokenId].length == 0) { for (i = token.x; i < upX; i++) { // check neighbors on top of area _tokenId = soldUnits[i][token.y - 1]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } // check neighbors on bottom of area _tokenId = soldUnits[i][upY]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } } for (j = token.y; j < upY; j++) { // check neighbors on left of area of area _tokenId = soldUnits[token.x - 1][j]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } // check neighbors on right of area of area _tokenId = soldUnits[upX][j]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } } } // increase price for (k = 0; k < neighboursArea[tokenId].length; k++) { Token storage _token = allMinedTokens[allTokensIndex[neighboursArea[tokenId][k]]]; _token.soldNearby = _token.soldNearby.add(1); _token.actualPrice = _token.actualPrice.add((_token.actualPrice.div(100))); emit TokenPriceIncreased(_token.id, _token.actualPrice, _tokenId, now); } } // move generated Units to sold array // generate siblings and put it there function copyToAllUnits(uint256 x, uint256 y, uint256 width, uint256 height, uint256 tokenId) internal { uint256 upX = x + width; // 5 uint256 upY = y + height; // 3 uint256 i; // 1 uint256 j; // 1 for (i = x; i < upX; i++) { for (j = y; j < upY; j++) { soldUnits[i][j] = tokenId; } } } function updateInternalState(Token minted, address _to) internal { uint256 lengthT = allMinedTokens.length; allMinedTokens.push(minted); allTokensIndex[minted.id] = lengthT; tokenOwner[minted.id] = _to; } } 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]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit 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) { return balances[_owner]; } } 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); emit 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; emit 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); emit 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BigIOERC20token is StandardToken, Ownable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public maxSupply; bool public allowedMinting; mapping(address => bool) public mintingAgents; mapping(address => bool) public stateChangeAgents; event MintERC20(address indexed _holder, uint256 _tokens); event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); modifier onlyMintingAgents () { require(mintingAgents[msg.sender]); _; } constructor (string _name, string _symbol, uint8 _decimals, uint256 _maxSupply) public StandardToken() { name = _name; symbol = _symbol; decimals = _decimals; maxSupply = _maxSupply; allowedMinting = true; mintingAgents[msg.sender] = true; } /// @notice update minting agent function updateMintingAgent(address _agent, bool _status) public onlyOwner { mintingAgents[_agent] = _status; } /// @notice allow to mint tokens function mint(address _holder, uint256 _tokens) public onlyMintingAgents() { require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply); totalSupply_ = totalSupply_.add(_tokens); balances[_holder] = balanceOf(_holder).add(_tokens); if (totalSupply_ == maxSupply) { allowedMinting = false; } emit MintERC20(_holder, _tokens); emit Transfer(0x0, _holder, _tokens); } } contract PricingStrategy { using SafeMath for uint256; function calculateMinPriceForNextRound(uint256 _tokenPrice, uint256 _minResalePercentage) public pure returns (uint256) { return _tokenPrice.add(_tokenPrice.div(100).mul(_minResalePercentage)); } function calculateSharesInTheRevenue(uint256 _prevTokenPrice, uint256 _newTokenPrice) public pure returns (uint256, uint256) { uint256 revenue = _newTokenPrice.sub(_prevTokenPrice); uint256 platformShare = revenue.mul(40).div(100); uint256 forPrevOwner = revenue.sub(platformShare); return (platformShare, forPrevOwner); } } /// @title Platform /// @author Applicature /// @notice It is front contract which is used to sell, re-sell tokens and initiate paying dividends contract Platform is Admin { using SafeMath for uint256; struct Offer { uint256 tokenId; uint256 offerId; address from; uint256 offeredPrice; uint256 tokenPrice; bool accepted; uint256 timestamp; } struct ArtWorkChangeRequest { address fromUser; uint256 tokenId; uint256 changeId; string meta; uint256 timestamp; bool isReviewed; } BigIoAdSpace public token; BigIOERC20token public erc20token; PricingStrategy public pricingStrategy; ArtWorkChangeRequest[] public artWorkChangeRequests; bool public isLogoInitied; uint256 public logoX = 35; uint256 public logoY = 18; Offer[] public offers; mapping(address => uint256) public pendingReturns; event Minted(address indexed _owner, uint256 _tokenId, uint256 _x, uint256 _y, uint256 _sizeA, uint256 _sizeB, uint256 _price, uint256 _platformTransfer, uint256 _timestamp); event Purchased(address indexed _from, address indexed _to, uint256 _tokenId, uint256 _price, uint256 _prevPrice, uint256 _prevOwnerTransfer, uint256 _platformTransfer, uint256 _timestamp); event OfferMade(address indexed _fromUser, uint256 _tokenId, uint256 _offerId, uint256 _offeredPrice, uint256 _timestamp); event OfferApproved(address indexed _owner, uint256 _tokenId, uint256 _offerId, uint256 _offeredPrice, uint256 _timestamp); event OfferDeclined(address indexed _fromUser, uint256 _tokenId, uint256 _offerId, uint256 _offeredPrice, uint256 _timestamp); event ArtWorkChangeRequestMade( address indexed _fromUser, uint256 _tokenId, uint256 _changeId, string _meta, uint256 _platformTransfer, uint256 _timestamp); event ArtWorkChangeRequestApproved( address indexed _fromUser, uint256 _tokenId, uint256 _changeId, string _meta, uint256 _timestamp); event ArtWorkChangeRequestDeclined( address indexed _fromUser, uint256 _tokenId, uint256 _changeId, string _meta, uint256 _timestamp); event RemovedMetaData(uint256 _tokenId, address _admin, string _meta, uint256 _timestamp); event ChangedOwnership(uint256 _tokenId, address _prevOwner, address _newOwner, uint256 _timestamp); constructor( address _platformWallet, // owner collects money address _token, address _erc20token, address _pricingStrategy, address _signer ) public { token = BigIoAdSpace(_token); erc20token = BigIOERC20token(_erc20token); platformWallet = _platformWallet; pricingStrategy = PricingStrategy(_pricingStrategy); signers[_signer] = true; // 30% tiers.push( Tier( 400, // amountInCenter 600, // amountInOuter 1 ether, // priceInCenter 0.4 ether, // priceInOuter 0, // soldInCenter 0, // soldInOuter false, // filledInCenter false // filledInOuter ) ); // 30% tiers.push( Tier( 400, 600, 1.2 ether, 0.6 ether, 0, 0, false, false ) ); // 30% tiers.push( Tier( 400, 600, 1.4 ether, 0.8 ether, 0, 0, false, false ) ); // 10% tiers.push( Tier( 144, 288, 1.6 ether, 1.0 ether, 0, 0, false, false ) ); } /// @notice init logo, call it as soon as possible /// call it after setting platform in the token /// Logo is BigIOToken which has 10*10 size and position in the center of map function initLogo() public onlyOwner { require(isLogoInitied == false); isLogoInitied = true; logoId = token.mint(platformWallet, logoX, logoY, 10, 10, 0 ether, 0 ether); token.setTokenMetadata(logoId, ""); updateTierStatus(100, 0); emit Minted(msg.sender, logoId, logoX, logoY, 10, 10, 0 ether, 0 ether, now); } function getPriceFor(uint256 x, uint256 y, uint256 sizeA, uint256 sizeB) public view returns(uint256 totalPrice, uint256 inner, uint256 outer) { (inner, outer) = preMinting(x, y, sizeA, sizeB); totalPrice = calculateTokenPrice(inner, outer); return (totalPrice, inner, outer); } /// @notice sell new tokens during the round 0 /// all except logo function buy( uint256 x, // top left coordinates uint256 y, // top left coordinates uint256 sizeA, // size/width of a square uint256 sizeB, // size/height of a square, uint8 _v, // component of signature bytes32 _r, // component of signature bytes32 _s // component of signature ) public notHalted() payable { address recoveredSigner = verify(keccak256(msg.sender), _v, _r, _s); require(signers[recoveredSigner] == true); require(msg.value > 0); internalBuy(x, y, sizeA, sizeB); } function internalBuy( uint256 x, // top left coordinates uint256 y, // top left coordinates uint256 sizeA, // size/width of a square uint256 sizeB // size/height of a square, ) internal { // get and validate current tier uint256 inner = 0; uint256 outer = 0; uint256 totalPrice = 0; (inner, outer) = preMinting(x, y, sizeA, sizeB); totalPrice = calculateTokenPrice(inner, outer); require(totalPrice <= msg.value); // try to mint and update current tier updateTierStatus(inner, outer); uint256 actualPrice = inner.mul(tiers[3].priceInCenter).add(outer.mul(tiers[3].priceInOuter)); if (msg.value > actualPrice) { actualPrice = msg.value; } uint256 tokenId = token.mint(msg.sender, x, y, sizeA, sizeB, msg.value, actualPrice); erc20token.mint(msg.sender, inner.add(outer)); transferEthers(platformWallet, msg.value); emit Minted(msg.sender, tokenId, x, y, sizeA, sizeB, msg.value, msg.value, now); } /// @notice allow user to make an offer after initial phase(re-sale) /// any offer minResalePercentage is accepted automatically function makeOffer( uint256 _tokenId, uint8 _v, // component of signature bytes32 _r, // component of signature bytes32 _s // component of signature ) public notHalted() payable { address recoveredSigner = verify(keccak256(msg.sender), _v, _r, _s); require(signers[recoveredSigner] == true); require(msg.sender != address(0)); require(msg.value > 0); uint256 currentPrice = getTokenPrice(_tokenId); require(currentPrice > 0); // special case for first sell of logo if (_tokenId == logoId && token.getCurrentPriceForToken(_tokenId) == 0) { require(msg.value >= logoPrice); //update token's state token.updateTokensState(logoId, msg.value); // mint erc20 tokens erc20token.mint(msg.sender, 100); transferEthers(platformWallet, msg.value); emit Purchased(0, msg.sender, _tokenId, msg.value, 0, 0, msg.value, now); return; } uint256 minPrice = pricingStrategy.calculateMinPriceForNextRound(currentPrice, minResalePercentage); require(msg.value >= minPrice); uint256 offerCounter = offers.length; offers.push(Offer(_tokenId, offerCounter, msg.sender, msg.value, currentPrice, false, now)); emit OfferMade(msg.sender, _tokenId, offerCounter, msg.value, now); // 2. check condition for approve and do it approve(offerCounter, _tokenId); } function getTokenPrice(uint256 _tokenId) public view returns (uint256 price) { uint256 actualPrice = token.getCurrentPriceForToken(_tokenId); // special case for first sell of logo if (_tokenId == logoId && actualPrice == 0) { require(logoPrice > 0); return logoPrice; } else { uint256 indexInner = 0; uint256 indexOuter = 0; bool hasInner; bool hasOuter; (hasInner, hasOuter) = token.getTokenScope(_tokenId); (indexInner, indexOuter) = getCurrentTierIndex(); if (_tokenId != logoId && hasInner) { require(indexInner == 100000); } if (hasOuter) { require(indexOuter == 100000); } return actualPrice; } } function getArtWorkChangeFee(uint256 _tokenId) public view returns (uint256 fee) { uint256 counter = token.getTokenUpdatedCounter(_tokenId); if (counter > 0) { return feeForArtWorkChangeRequest; } return feeForFirstArtWorkChangeRequest; } /// @notice it allows token owner to create art work change request /// first user upload 2 images /// then do call this function /// admin can reject or approve it function artWorkChangeRequest(uint256 _tokenId, string _meta, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { address recoveredSigner = verify(keccak256(_meta), _v, _r, _s); require(signers[recoveredSigner] == true); require(msg.sender == token.getOwner(_tokenId)); uint256 fee = getArtWorkChangeFee(_tokenId); require(msg.value >= fee); uint256 changeRequestCounter = artWorkChangeRequests.length; artWorkChangeRequests.push( ArtWorkChangeRequest(msg.sender, _tokenId, changeRequestCounter, _meta, now, false) ); token.increaseUpdateMetadataCounter(_tokenId); transferEthers(platformWallet, msg.value); emit ArtWorkChangeRequestMade(msg.sender, _tokenId, changeRequestCounter, _meta, msg.value, now); return changeRequestCounter; } function artWorkChangeApprove(uint256 _index, uint256 _tokenId, bool approve) public onlyAdmin { ArtWorkChangeRequest storage request = artWorkChangeRequests[_index]; require(false == request.isReviewed); require(_tokenId == request.tokenId); request.isReviewed = true; if (approve) { token.setTokenMetadata(_tokenId, request.meta); emit ArtWorkChangeRequestApproved( request.fromUser, request.tokenId, request.changeId, request.meta, now ); } else { emit ArtWorkChangeRequestDeclined( request.fromUser, request.tokenId, request.changeId, request.meta, now ); } } function artWorkChangeByAdmin(uint256 _tokenId, string _meta, uint256 _changeId) public onlyAdmin { token.setTokenMetadata(_tokenId, _meta); emit ArtWorkChangeRequestApproved( msg.sender, _tokenId, _changeId, _meta, now ); } function changeTokenOwnerByAdmin(uint256 _tokenId, address _newOwner) public onlyAdmin { address prevOwner = token.getOwner(_tokenId); token.updateOwner(_tokenId, _newOwner, prevOwner); emit ChangedOwnership(_tokenId, prevOwner, _newOwner, now); string memory meta = token.getMetadata(_tokenId); token.removeTokenMetadata(_tokenId); emit RemovedMetaData(_tokenId, msg.sender, meta, now); } /// @return tokenId, x, y, sizeA, sizeB, price function getTokenData(uint256 _tokenId) public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return token.getTokenData(_tokenId); } function getMetaData(uint256 _tokenId) public view returns(string) { return token.getMetadata(_tokenId); } /// @notice Withdraw a bid that was overbid and platform owner share function claim() public returns (bool) { return claimInternal(msg.sender); } /// @notice Withdraw (for cold storage wallet) a bid that was overbid and platform owner share function claimByAddress(address _address) public returns (bool) { return claimInternal(_address); } function claimInternal(address _address) internal returns (bool) { require(_address != address(0)); uint256 amount = pendingReturns[_address]; if (amount == 0) { return; } pendingReturns[_address] = 0; _address.transfer(amount); return true; } /// @return index of current tiers, if 100000(cannot use -1) then round 0 finished /// and we need to move to re-sale function getCurrentTierIndex() public view returns (uint256, uint256) { // cannot use -1 // so use not possible value for tiers.length uint256 indexInner = 100000; uint256 indexOuter = 100000; for (uint256 i = 0; i < tiers.length; i++) { if (!tiers[i].filledInCenter) { indexInner = i; break; } } for (uint256 k = 0; k < tiers.length; k++) { if (!tiers[k].filledInOuter) { indexOuter = k; break; } } return (indexInner, indexOuter); } /// @return current tier stats /// index of current tiers, if 100000(cannot use -1) then initial sale is finished /// works only during the initial phase function getCurrentTierStats() public view returns (uint256 indexInner, uint256 indexOuter, uint256 availableInner, uint256 availableInOuter, uint256 priceInCenter, uint256 priceInOuter, uint256 nextPriceInCenter, uint256 nextPriceInOuter) { indexInner = 100000; indexOuter = 100000; for (uint256 i = 0; i < tiers.length; i++) { if (!tiers[i].filledInCenter) { indexInner = i; break; } } for (uint256 k = 0; k < tiers.length; k++) { if (!tiers[k].filledInOuter) { indexOuter = k; break; } } Tier storage tier; if (indexInner != 100000) { tier = tiers[indexInner]; availableInner = tier.amountInCenter.sub(tier.soldInCenter); priceInCenter = tier.priceInCenter; if (indexInner < 3) { nextPriceInCenter = tiers[indexInner + 1].priceInCenter; } } if (indexOuter != 100000) { tier = tiers[indexOuter]; availableInOuter = tier.amountInOuter.sub(tier.soldInOuter); priceInOuter = tier.priceInOuter; if (indexOuter < 3) { nextPriceInOuter = tiers[indexOuter + 1].priceInOuter; } } } function calculateAmountOfUnits(uint256 sizeA, uint256 sizeB) public pure returns (uint256) { return sizeA.mul(sizeB); } /// @notice approve the offer function approve(uint256 _index, uint256 _tokenId) internal { Offer memory localOffer = offers[_index]; address newOwner = localOffer.from; address prevOwner = token.getOwner(_tokenId); uint256 platformShare; uint256 forPrevOwner; uint256 soldPrice = token.getTokenSoldPrice(_tokenId); (platformShare, forPrevOwner) = pricingStrategy.calculateSharesInTheRevenue( soldPrice, localOffer.offeredPrice); //update token's state token.updateTokensState(_tokenId, localOffer.offeredPrice); // update owner token.updateOwner(_tokenId, newOwner, prevOwner); localOffer.accepted = true; transferEthers(platformWallet, platformShare); transferEthers(prevOwner, forPrevOwner.add(soldPrice)); emit OfferApproved(newOwner, _tokenId, localOffer.offerId, localOffer.offeredPrice, now); emit Purchased(prevOwner, newOwner, _tokenId, localOffer.offeredPrice, soldPrice, forPrevOwner.add(soldPrice), platformShare, now); afterApproveAction(_tokenId); } function transferEthers(address _address, uint256 _wei) internal { if (isContract(_address)) { pendingReturns[_address] = pendingReturns[_address].add(_wei); } else { _address.transfer(_wei); } } function preMinting(uint256 x, uint256 y, uint256 sizeA, uint256 sizeB) internal view returns (uint256, uint256) { // calculate units for token uint256 total = 0; uint256 inner = 0; uint256 outer = 0; (total, inner) = token.calculateCounters(x, y, sizeA, sizeB); outer = total.sub(inner); require(total <= 100); return (inner, outer); } function updateTierStatus(uint256 inner, uint256 outer) internal { uint256 leftInner = inner; uint256 leftOuter = outer; for (uint256 i = 0; i < 4; i++) { Tier storage tier = tiers[i]; if (leftInner > 0 && tier.filledInCenter == false) { uint256 availableInner = tier.amountInCenter.sub(tier.soldInCenter); if (availableInner > leftInner) { tier.soldInCenter = tier.soldInCenter.add(leftInner); leftInner = 0; } else { tier.filledInCenter = true; tier.soldInCenter = tier.amountInCenter; leftInner = leftInner.sub(availableInner); } } if (leftOuter > 0 && tier.filledInOuter == false) { uint256 availableOuter = tier.amountInOuter.sub(tier.soldInOuter); if (availableOuter > leftOuter) { tier.soldInOuter = tier.soldInOuter.add(leftOuter); leftOuter = 0; } else { tier.filledInOuter = true; tier.soldInOuter = tier.amountInOuter; leftOuter = leftOuter.sub(availableOuter); } } } require(leftInner == 0 && leftOuter == 0); } function calculateTokenPrice(uint256 inner, uint256 outer) public view returns (uint256 price) { uint256 leftInner = inner; uint256 leftOuter = outer; for (uint256 i = 0; i < 4; i++) { Tier storage tier = tiers[i]; if (leftInner > 0 && tier.filledInCenter == false) { uint256 availableInner = tier.amountInCenter.sub(tier.soldInCenter); if (availableInner > leftInner) { price = price.add(leftInner.mul(tier.priceInCenter)); leftInner = 0; } else { price = price.add(availableInner.mul(tier.priceInCenter)); leftInner = leftInner.sub(availableInner); } } if (leftOuter > 0 && tier.filledInOuter == false) { uint256 availableOuter = tier.amountInOuter.sub(tier.soldInOuter); if (availableOuter > leftOuter) { price = price.add(leftOuter.mul(tier.priceInOuter)); leftOuter = 0; } else { price = price.add(availableOuter.mul(tier.priceInOuter)); leftOuter = leftOuter.sub(availableOuter); } } } require(leftInner == 0 && leftOuter == 0); } function minPriceForNextRound(uint256 _tokenId) public view returns (uint256) { if (_tokenId == logoId && token.getCurrentPriceForToken(_tokenId) == 0) { return logoPrice; } else { // @TODO: check if sold-out uint256 currentPrice = getTokenPrice(_tokenId); uint256 minPrice = pricingStrategy.calculateMinPriceForNextRound(currentPrice, minResalePercentage); return minPrice; } } function afterApproveAction(uint256 _tokenId) internal { uint256 indexInner = 100000; uint256 indexOuter = 100000; bool hasInner; bool hasOuter; (hasInner, hasOuter) = token.getTokenScope(_tokenId); (indexInner, indexOuter) = getCurrentTierIndex(); if (hasInner && hasOuter && indexInner == 100000 && indexOuter == 100000) { token.increasePriceForNeighbours(_tokenId); } else if (!hasInner && hasOuter && indexOuter == 100000) { token.increasePriceForNeighbours(_tokenId); } else if (!hasOuter && hasInner && indexInner == 100000) { token.increasePriceForNeighbours(_tokenId); } } function canBuyExistentToken(uint256 _tokenId) public view returns (uint256 _allowed) { uint256 indexInner = 0; uint256 indexOuter = 0; bool hasInner; bool hasOuter; (hasInner, hasOuter) = token.getTokenScope(_tokenId); (indexInner, indexOuter) = getCurrentTierIndex(); if (token.getCurrentPriceForToken(_tokenId) == 0 && logoPrice == 0) { return 4; } if (_tokenId != logoId && hasInner && indexInner != 100000) { return 2; } if (hasOuter && indexOuter != 100000) { return 3; } return 1; } }
check neighbors on top of area check neighbors on left of area of area increase price
function increasePriceForNeighbours(uint256 tokenId) public onlyPlatform { Token memory token = allMinedTokens[allTokensIndex[tokenId]]; uint256 upX = token.x.add(token.sizeA); uint256 upY = token.y.add(token.sizeB); uint256 i; uint256 j; uint256 k; uint256 _tokenId; if (neighboursArea[tokenId].length == 0) { for (i = token.x; i < upX; i++) { _tokenId = soldUnits[i][token.y - 1]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } } for (j = token.y; j < upY; j++) { _tokenId = soldUnits[token.x - 1][j]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); } if (!neighbours[_tokenId][tokenId]) { neighbours[_tokenId][tokenId] = true; neighboursArea[_tokenId].push(tokenId); } } } } for (k = 0; k < neighboursArea[tokenId].length; k++) { Token storage _token = allMinedTokens[allTokensIndex[neighboursArea[tokenId][k]]]; _token.soldNearby = _token.soldNearby.add(1); _token.actualPrice = _token.actualPrice.add((_token.actualPrice.div(100))); emit TokenPriceIncreased(_token.id, _token.actualPrice, _tokenId, now); } }
462,001
./full_match/137/0xddC11E9755426Dcc21cA8F60eE2544c41624bd95/sources/_xaya/democrit-evm/contracts/LimitBuying.sol
Returns the data for a sell deposit. They are identified and queried by vault ID. If the vault does not exist or is not a sell deposit, then a null struct will be returned./
function getSellDeposit (uint vaultId) public view returns (CompleteSellDeposit memory) { if (!sellDeposits[vaultId]) { CompleteSellDeposit memory nullDeposit; return nullDeposit; } VaultManager.VaultData memory vault = vm.getVault (vaultId); assert (vault.balance > 0); return CompleteSellDeposit ({ vaultId: vaultId, owner: vault.founder, asset: vault.asset, amount: vault.balance }); }
3,767,990
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @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); } } } } /** * @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)); } } /* * @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; } /** * @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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @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. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _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()); } uint256[49] private __gap; } /** * @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; } /** * @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); } /** * @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 SafeMathUpgradeable { /** * @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; } } /** * @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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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"); } } } interface IERC20Detailed { function decimals() external view returns (uint8); } contract DeHiveTokensale is OwnableUpgradeable, PausableUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /** * EVENTS **/ event DHVPurchased(address indexed user, address indexed purchaseToken, uint256 dhvAmount); event TokensClaimed(address indexed user, uint256 dhvAmount); /** * CONSTANTS **/ // *** TOKENSALE PARAMETERS START *** uint256 public constant PRECISION = 1000000; //Up to 0.000001 uint256 public constant PRE_SALE_START = 1616594400; //Mar 24 2021 14:00:00 GMT uint256 public constant PRE_SALE_END = 1616803140; //Mar 26 2021 23:59:00 GMT uint256 public constant PUBLIC_SALE_START = 1618408800; //Apr 14 2021 14:00:00 GMT uint256 public constant PUBLIC_SALE_END = 1618790340; //Apr 18 2021 23:59:00 GMT uint256 public constant PRE_SALE_DHV_POOL = 450000 * 10 ** 18; // 5% DHV in total in presale pool uint256 public constant PRE_SALE_DHV_NUX_POOL = 50000 * 10 ** 18; // uint256 public PUBLIC_SALE_DHV_POOL; // 11% DHV in public sale pool uint256 private constant WITHDRAWAL_PERIOD = 365 * 24 * 60 * 60; //1 year // *** TOKENSALE PARAMETERS END *** /*** * STORAGE ***/ uint256 public maxTokensAmount; uint256 public maxGasPrice; // *** VESTING PARAMETERS START *** uint256 public vestingStart; uint256 public constant vestingDuration = 305 days; //305 days - until Apr 30 2021 00:00:00 GMT // *** VESTING PARAMETERS END *** address public DHVToken; address internal USDTToken; /*= 0xdAC17F958D2ee523a2206206994597C13D831ec7 */ address internal DAIToken; /*= 0x6B175474E89094C44Da98b954EedeAC495271d0F*/ address internal NUXToken; /*= 0x89bD2E7e388fAB44AE88BEf4e1AD12b4F1E0911c*/ mapping (address => uint256) public purchased; mapping (address => uint256) internal _claimed; uint256 public purchasedWithNUX; uint256 public purchasedPreSale; uint256 public purchasedPublicSale; uint256 public ETHRate; mapping (address => uint256) public rates; address private _treasury; /*** * MODIFIERS ***/ /** * @dev Throws if called with not supported token. */ modifier supportedCoin(address _token) { require(_token == USDTToken || _token == DAIToken, "Token not supported"); _; } /** * @dev Throws if called when no ongoing pre-sale or public sale. */ modifier onlySale() { require(_isPreSale() || _isPublicSale(), "Sale stages are over or not started"); _; } /** * @dev Throws if called when no ongoing pre-sale or public sale. */ modifier onlyPreSale() { require(_isPreSale(), "Presale stages are over or not started"); _; } /** * @dev Throws if sale stage is ongoing. */ modifier notOnSale() { require(!_isPreSale(), "Presale is not over"); require(!_isPublicSale(), "Sale is not over"); _; } /** * @dev Throws if gas price exceeds gas limit. */ modifier correctGas() { require(maxGasPrice == 0 || tx.gasprice <= maxGasPrice, "Gas price exceeds limit"); _; } /*** * INITIALIZER AND SETTINGS ***/ /** * @notice Initializes the contract with correct addresses settings * @param treasury Address of the DeHive protocol's treasury where funds from sale go to * @param dhv DHVToken mainnet address */ function initialize(address treasury, address dhv) public initializer { require(treasury != address(0), "Zero address"); require(dhv != address(0), "Zero address"); __Ownable_init(); __Pausable_init(); _treasury = treasury; DHVToken = dhv; DAIToken = 0x6B175474E89094C44Da98b954EedeAC495271d0F; USDTToken = 0xdAC17F958D2ee523a2206206994597C13D831ec7; NUXToken = 0x89bD2E7e388fAB44AE88BEf4e1AD12b4F1E0911c; vestingStart = 0; maxTokensAmount = 49600 * (10 ** 18); // around 50 ETH PUBLIC_SALE_DHV_POOL = 1100000 * 10 ** 18; // 11% of sale pool } /** * @notice Updates current vesting start time. Can be used once * @param _vestingStart New vesting start time */ function adminSetVestingStart(uint256 _vestingStart) virtual external onlyOwner{ require(vestingStart == 0, "Vesting start is already set"); require(_vestingStart > PUBLIC_SALE_END && block.timestamp < _vestingStart, "Incorrect time provided"); vestingStart = _vestingStart; } /** * @notice Sets the rate for the chosen token based on the contracts precision * @param _token ERC20 token address or zero address for ETH * @param _rate Exchange rate based on precision (e.g. _rate = PRECISION corresponds to 1:1) */ function adminSetRates(address _token, uint256 _rate) external onlyOwner { if (_token == address(0)) ETHRate = _rate; else rates[_token] = _rate; } /** * @notice Allows owner to change the treasury address. Treasury is the address where all funds from sale go to * @param treasury New treasury address */ function adminSetTreasury(address treasury) external onlyOwner { _treasury = treasury; } /** * @notice Allows owner to change max allowed DHV token per address. * @param _maxDHV New max DHV amount */ function adminSetMaxDHV(uint256 _maxDHV) external onlyOwner { maxTokensAmount = _maxDHV; } /** * @notice Allows owner to change the max allowed gas price. Prevents gas wars * @param _maxGasPrice New max gas price */ function adminSetMaxGasPrice(uint256 _maxGasPrice) external onlyOwner { maxGasPrice = _maxGasPrice; } /** * @notice Updates public sales pool maximum * @param _publicPool New public pool DHV maximum value */ function adminSetPublicPool(uint256 _publicPool) external onlyOwner { PUBLIC_SALE_DHV_POOL = _publicPool; } /** * @notice Stops purchase functions. Owner only */ function adminPause() external onlyOwner { _pause(); } /** * @notice Unpauses purchase functions. Owner only */ function adminUnpause() external onlyOwner { _unpause(); } /*** * PURCHASE FUNCTIONS ***/ /** * @notice For purchase with ETH */ receive() external virtual payable onlySale whenNotPaused { _purchaseDHVwithETH(); } /** * @notice For purchase with allowed stablecoin (USDT and DAI) * @param ERC20token Address of the token to be paid in * @param ERC20amount Amount of the token to be paid in */ function purchaseDHVwithERC20(address ERC20token, uint256 ERC20amount) external onlySale supportedCoin(ERC20token) whenNotPaused correctGas { require(ERC20amount > 0, "Zero amount"); uint256 purchaseAmount = _calcPurchaseAmount(ERC20token, ERC20amount); require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded"); if (_isPreSale()) { require(purchasedPreSale.add(purchaseAmount) <= PRE_SALE_DHV_POOL, "Not enough DHV in presale pool"); purchasedPreSale = purchasedPreSale.add(purchaseAmount); } else { require(purchaseAmount <= publicSaleAvailableDHV(), "Not enough DHV in sale pool"); purchasedPublicSale = purchasedPublicSale.add(purchaseAmount); } purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount); IERC20Upgradeable(ERC20token).safeTransferFrom(_msgSender(), _treasury, ERC20amount); // send ERC20 to Treasury emit DHVPurchased(_msgSender(), ERC20token, purchaseAmount); } /** * @notice For purchase with NUX token only. Available only for tokensale * @param nuxAmount Amount of the NUX token */ function purchaseDHVwithNUX(uint256 nuxAmount) external onlyPreSale whenNotPaused correctGas { require(nuxAmount > 0, "Zero amount"); uint256 purchaseAmount = _calcPurchaseAmount(NUXToken, nuxAmount); require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded"); require(purchasedWithNUX.add(purchaseAmount) <= PRE_SALE_DHV_NUX_POOL, "Not enough DHV in NUX pool"); purchasedWithNUX = purchasedWithNUX.add(purchaseAmount); purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount); IERC20Upgradeable(NUXToken).safeTransferFrom(_msgSender(), _treasury, nuxAmount); emit DHVPurchased(_msgSender(), NUXToken, purchaseAmount); } /** * @notice For purchase with ETH. ETH is left on the contract until withdrawn to treasury */ function purchaseDHVwithETH() external payable onlySale whenNotPaused { require(msg.value > 0, "No ETH sent"); _purchaseDHVwithETH(); } function _purchaseDHVwithETH() correctGas private { uint256 purchaseAmount = _calcEthPurchaseAmount(msg.value); require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded"); if (_isPreSale()) { require(purchasedPreSale.add(purchaseAmount) <= PRE_SALE_DHV_POOL, "Not enough DHV in presale pool"); purchasedPreSale = purchasedPreSale.add(purchaseAmount); } else { require(purchaseAmount <= publicSaleAvailableDHV(), "Not enough DHV in sale pool"); purchasedPublicSale = purchasedPublicSale.add(purchaseAmount); } purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount); payable(_treasury).transfer(msg.value); emit DHVPurchased(_msgSender(), address(0), purchaseAmount); } /** * @notice Function to get available on public sale amount of DHV * @notice Unsold NUX pool and pre-sale pool go to public sale * @return The amount of the token released. */ function publicSaleAvailableDHV() public view returns(uint256) { return (PUBLIC_SALE_DHV_POOL + PRE_SALE_DHV_POOL.sub(purchasedPreSale) + PRE_SALE_DHV_NUX_POOL.sub(purchasedWithNUX)).sub(purchasedPublicSale); } /** * @notice Function for the administrator to withdraw token (except DHV) * @notice Withdrawals allowed only if there is no sale pending stage * @param ERC20token Address of ERC20 token to withdraw from the contract */ function adminWithdrawERC20(address ERC20token) external onlyOwner notOnSale { require(ERC20token != DHVToken || _canWithdrawDHV(), "DHV withdrawal is forbidden"); uint256 tokenBalance = IERC20Upgradeable(ERC20token).balanceOf(address(this)); IERC20Upgradeable(ERC20token).safeTransfer(_treasury, tokenBalance); } /** * @notice Function for the administrator to withdraw ETH for refunds * @notice Withdrawals allowed only if there is no sale pending stage */ function adminWithdraw() external onlyOwner notOnSale { require(address(this).balance > 0, "Nothing to withdraw"); (bool success, ) = _treasury.call{value: address(this).balance}(""); require(success, "Transfer failed"); } /** * @notice Returns DHV amount for 1 external token * @param _token External toke (DAI, USDT, NUX, 0 address for ETH) */ function rateForToken(address _token) external view returns(uint256) { if (_token == address(0)) { return _calcEthPurchaseAmount(10**18); } else { return _calcPurchaseAmount(_token, 10**( uint256(IERC20Detailed(_token).decimals()) )); } } /*** * VESTING INTERFACE ***/ /** * @notice Transfers available for claim vested tokens to the user. */ function claim() external { require(vestingStart!=0, "Vesting start is not set"); require(_isPublicSaleOver(), "Not allowed to claim now"); uint256 unclaimed = claimable(_msgSender()); require(unclaimed > 0, "TokenVesting: no tokens are due"); _claimed[_msgSender()] = _claimed[_msgSender()].add(unclaimed); IERC20Upgradeable(DHVToken).safeTransfer(_msgSender(), unclaimed); emit TokensClaimed(_msgSender(), unclaimed); } /** * @notice Gets the amount of tokens the user has already claimed * @param _user Address of the user who purchased tokens * @return The amount of the token claimed. */ function claimed(address _user) external view returns (uint256) { return _claimed[_user]; } /** * @notice Calculates the amount that has already vested but hasn't been claimed yet. * @param _user Address of the user who purchased tokens * @return The amount of the token vested and unclaimed. */ function claimable(address _user) public view returns (uint256) { return _vestedAmount(_user).sub(_claimed[_user]); } /** * @dev Calculates the amount that has already vested. * @param _user Address of the user who purchased tokens * @return Amount of DHV already vested */ function _vestedAmount(address _user) private view returns (uint256) { if (block.timestamp >= vestingStart.add(vestingDuration)) { return purchased[_user]; } else { return purchased[_user].mul(block.timestamp.sub(vestingStart)).div(vestingDuration); } } /*** * INTERNAL HELPERS ***/ /** * @dev Checks if presale stage is on-going. * @return True is presale is active */ function _isPreSale() virtual internal view returns (bool) { return (block.timestamp >= PRE_SALE_START && block.timestamp < PRE_SALE_END); } /** * @dev Checks if public sale stage is on-going. * @return True is public sale is active */ function _isPublicSale() virtual internal view returns (bool) { return (block.timestamp >= PUBLIC_SALE_START && block.timestamp < PUBLIC_SALE_END); } /** * @dev Checks if public sale stage is over. * @return True is public sale is over */ function _isPublicSaleOver() virtual internal view returns (bool) { return (block.timestamp >= PUBLIC_SALE_END); } /** * @dev Checks if public sale stage is over. * @return True is public sale is over */ function _canWithdrawDHV() virtual internal view returns (bool) { return (block.timestamp >= vestingStart.add(WITHDRAWAL_PERIOD) ); } /** * @dev Calculates DHV amount based on rate and token. * @param _token Supported ERC20 token * @param _amount Token amount to convert to DHV * @return DHV amount */ function _calcPurchaseAmount(address _token, uint256 _amount) private view returns (uint256) { uint256 purchaseAmount = _amount.mul(rates[_token]).div(PRECISION); require(purchaseAmount > 0, "Rates not set"); uint8 _decimals = IERC20Detailed(_token).decimals(); if (_decimals < 18) { purchaseAmount = purchaseAmount.mul(10 ** (18 - uint256(_decimals))); } return purchaseAmount; } /** * @dev Calculates DHV amount based on rate and ETH amount. * @param _amount ETH amount to convert to DHV * @return DHV amount */ function _calcEthPurchaseAmount(uint256 _amount) private view returns (uint256) { uint256 purchaseAmount = _amount.mul(ETHRate).div(PRECISION); require(purchaseAmount > 0, "Rates not set"); return purchaseAmount; } }
For purchase with allowed stablecoin (USDT and DAI) ERC20token Address of the token to be paid in ERC20amount Amount of the token to be paid in/
function purchaseDHVwithERC20(address ERC20token, uint256 ERC20amount) external onlySale supportedCoin(ERC20token) whenNotPaused correctGas { require(ERC20amount > 0, "Zero amount"); uint256 purchaseAmount = _calcPurchaseAmount(ERC20token, ERC20amount); require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded"); if (_isPreSale()) { require(purchasedPreSale.add(purchaseAmount) <= PRE_SALE_DHV_POOL, "Not enough DHV in presale pool"); purchasedPreSale = purchasedPreSale.add(purchaseAmount); require(purchaseAmount <= publicSaleAvailableDHV(), "Not enough DHV in sale pool"); purchasedPublicSale = purchasedPublicSale.add(purchaseAmount); } purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount); emit DHVPurchased(_msgSender(), ERC20token, purchaseAmount); }
10,225,412
./partial_match/1/0xc3ED798159e449d224DE05515385F86C1d10608F/sources/AllMarketsV2.sol
Get market cooldown time return the time upto which user can raise the dispute after the market is settled/
function marketCoolDownTime(uint256 _marketId) public view returns(uint256) { return marketDataExtended[_marketId].settleTime + (marketBasicData[_marketId].predictionTime / 4); }
2,788,266
// Sources flattened with hardhat v2.6.8 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.3.2 // 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); } // File @openzeppelin/contracts/utils/Address.sol@v4.3.2 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); } } } } // File @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol@v4.3.2 pragma solidity ^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 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"); } } } // File @openzeppelin/contracts/utils/structs/EnumerableSet.sol@v4.3.2 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; } } // File @openzeppelin/contracts/security/ReentrancyGuard.sol@v4.3.2 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; } } // File contracts/pool/HCPEPool.sol pragma solidity >=0.8.9; /** * @title HC PE Pool Contract * @author HASHLAND-TEAM * @notice In this contract PE round users can harvest HC */ contract HCPEPool is ReentrancyGuard { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; IERC20 public hc; uint256 public constant blockPerDay = 28800; uint256 public constant blockPerYear = blockPerDay * 365; uint256 public constant blockPerQuarter = blockPerYear / 4; uint256 public constant hcStartBlock = 12507000; uint256 public constant releaseStartBlock = hcStartBlock + blockPerQuarter; uint256 public constant releaseEndBlock = releaseStartBlock + blockPerYear; uint256 public constant releasedTotalToken = (120e4 * 1e18 * 90) / 100; uint256 public constant tokenPerBlock = releasedTotalToken / blockPerYear; uint256 public lastRewardBlock = releaseStartBlock; uint256 public stake; uint256 public accTokenPerStake; uint256 public releasedToken; uint256 public harvestedToken; mapping(address => uint256) public userStake; mapping(address => uint256) public userLastAccTokenPerStake; mapping(address => uint256) public userStoredToken; mapping(address => uint256) public userHarvestedToken; EnumerableSet.AddressSet private users; event HarvestToken(address indexed user, uint256 amount); /** * @param hcAddr Initialize HC Address * @param userAddrs Initialize users * @param userStakes Initialize user stake */ constructor( address hcAddr, address[] memory userAddrs, uint256[] memory userStakes ) { require( userAddrs.length == userStakes.length, "Data length does not match" ); hc = IERC20(hcAddr); for (uint256 i = 0; i < userAddrs.length; i++) { userStake[userAddrs[i]] += userStakes[i]; stake += userStakes[i]; users.add(userAddrs[i]); } } /** * @dev Harvest Token */ function harvestToken() external nonReentrant { updatePool(); uint256 pendingToken = (userStake[msg.sender] * (accTokenPerStake - userLastAccTokenPerStake[msg.sender])) / 1e18; uint256 amount = userStoredToken[msg.sender] + pendingToken; require(amount > 0, "Not enough token to harvest"); userStoredToken[msg.sender] = 0; userLastAccTokenPerStake[msg.sender] = accTokenPerStake; userHarvestedToken[msg.sender] += amount; harvestedToken += amount; hc.safeTransfer(msg.sender, amount); emit HarvestToken(msg.sender, amount); } /** * @dev Get Token Total Rewards of a User */ function getTokenTotalRewards(address user) external view returns (uint256) { return userHarvestedToken[user] + getTokenRewards(user); } /** * @dev Get Users Length */ function getUsersLength() external view returns (uint256) { return users.length(); } /** * @dev Get Users by Size */ function getUsersBySize(uint256 cursor, uint256 size) external view returns (address[] memory, uint256) { uint256 length = size; if (length > users.length() - cursor) { length = users.length() - cursor; } address[] memory values = new address[](length); for (uint256 i = 0; i < length; i++) { values[i] = users.at(cursor + i); } return (values, cursor + length); } /** * @dev Update Pool */ function updatePool() public { if (block.number <= lastRewardBlock) { return; } uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { uint256 amount = tokenPerBlock * (rewardsBlock - lastRewardBlock); accTokenPerStake += (amount * 1e18) / stake; releasedToken += amount; } lastRewardBlock = block.number; } /** * @dev Get Token Rewards of a User */ function getTokenRewards(address user) public view returns (uint256) { uint256 accTokenPerStakeTemp = accTokenPerStake; uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { accTokenPerStakeTemp += (tokenPerBlock * (rewardsBlock - lastRewardBlock) * 1e18) / stake; } return userStoredToken[user] + ((userStake[user] * (accTokenPerStakeTemp - userLastAccTokenPerStake[user])) / 1e18); } }
Get Token Rewards of a User/
function getTokenRewards(address user) public view returns (uint256) { uint256 accTokenPerStakeTemp = accTokenPerStake; uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { accTokenPerStakeTemp += (tokenPerBlock * (rewardsBlock - lastRewardBlock) * 1e18) / stake; } return userStoredToken[user] + ((userStake[user] * (accTokenPerStakeTemp - userLastAccTokenPerStake[user])) / 1e18); }
12,868,313
./full_match/43113/0x8292f7Ab43eEDb0bAFd07702fFa2a7052C02666f/sources/project_/contracts/BaseContracts/BaseDistributor.sol
Distribute USDC to the holding address of each NFT collection Address of the ERC721 contract amount Amount of USDC to distribute in regular terms Only callable by the ADMIN role/ Get the supply of NFTs Calculate the amount of USDC to send to each holding address, format decimals Send vig after formatting decimals Use a safeTransferFrom to send the USDC to each holding address
function distribute(address collection, uint256 amount) external onlyRole(DISTRIBUTOR) { uint256 supply = IERC721(collection).totalSupply(); require(supply > 0, "No nfts in this collection"); uint256 vigorish = amount * (vig / 10000); uint256 amtInfo = amount - vigorish; uint256 sendAmount = (amtInfo * (10 ** usdc.decimals())) / supply; vigorish = vigorish * (10 ** usdc.decimals()); usdc.transferFrom(msg.sender, vigAdd, vigorish); for (uint256 i = 0; i < supply; i++) { usdc.transferFrom(msg.sender, IERC721(collection).ownerOf(i), sendAmount); } emit Distributed(collection, sendAmount); }
7,147,751
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @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; } } /** * @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. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ 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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // The functionality that all derivative contracts expose to the admin. interface AdminInterface { // Initiates the shutdown process, in case of an emergency. function emergencyShutdown() external; // A core contract method called immediately before or after any financial transaction. It pays fees and moves money // between margin accounts to make sure they reflect the NAV of the contract. function remargin() external; } // This interface allows contracts to query a verified, trusted price. interface OracleInterface { // Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available. // Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if // the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this // method. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable); // Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if // the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call // this method. function getPrice(bytes32 identifier, uint time) external view returns (int price); // Returns whether the Oracle provides verified prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // An event fired when a request for a (identifier, time) pair is made. event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time); // An event fired when a verified price is available for a (identifier, time) pair. event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price); } interface RegistryInterface { struct RegisteredDerivative { address derivativeAddress; address derivativeCreator; } // Registers a new derivative. Only authorized derivative creators can call this method. function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; // Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call // this method. function addDerivativeCreator(address derivativeCreator) external; // Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this // method. function removeDerivativeCreator(address derivativeCreator) external; // Returns whether the derivative has been registered with the registry (and is therefore an authorized participant // in the UMA system). function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); // Returns a list of all derivatives that are associated with a particular party. function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives); // Returns all registered derivatives. function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives); // Returns whether an address is authorized to register new derivatives. function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized); } contract Testable is Ownable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } modifier onlyIfTest { require(isTest); _; } function setCurrentTime(uint _time) external onlyOwner onlyIfTest { currentTime = _time; } function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract Withdrawable is Ownable { // Withdraws ETH from the contract. function withdraw(uint amount) external onlyOwner { msg.sender.transfer(amount); } // Withdraws ERC20 tokens from the contract. function withdrawErc20(address erc20Address, uint amount) external onlyOwner { IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } } // Implements an oracle that allows the owner to push prices for queries that have been made. contract CentralizedOracle is OracleInterface, Withdrawable, Testable { using SafeMath for uint; // This contract doesn't implement the voting routine, and naively indicates that all requested prices will be // available in a week. uint constant private SECONDS_IN_WEEK = 60*60*24*7; // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int price; // Time the verified price became available. uint verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint time; } // The set of identifiers the oracle can provide verified prices for. mapping(bytes32 => bool) private supportedIdentifiers; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; // Registry to verify that a derivative is approved to use the Oracle. RegistryInterface private registry; constructor(address _registry, bool _isTest) public Testable(_isTest) { registry = RegistryInterface(_registry); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime) { // Ensure that the caller has been registered with the Oracle before processing the request. require(registry.isDerivativeRegistered(msg.sender)); require(supportedIdentifiers[identifier]); Price storage lookup = verifiedPrices[identifier][time]; if (lookup.isAvailable) { // We already have a price, return 0 to indicate that. return 0; } else if (queryIndices[identifier][time].isValid) { // We already have a pending query, don't need to do anything. return getCurrentTime().add(SECONDS_IN_WEEK); } else { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); emit VerifiedPriceRequested(identifier, time); return getCurrentTime().add(SECONDS_IN_WEEK); } } // Pushes the verified price for a requested query. function pushPrice(bytes32 identifier, uint time, int price) external onlyOwner { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); emit VerifiedPriceAvailable(identifier, time, price); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint lastIndex = requestedPrices.length.sub(1); if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } requestedPrices.length = requestedPrices.length.sub(1); } // Adds the provided identifier as a supported identifier. function addSupportedIdentifier(bytes32 identifier) external onlyOwner { if(!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit AddSupportedIdentifier(identifier); } } // Calls emergencyShutdown() on the provided derivative. function callEmergencyShutdown(address derivative) external onlyOwner { AdminInterface admin = AdminInterface(derivative); admin.emergencyShutdown(); } // Calls remargin() on the provided derivative. function callRemargin(address derivative) external onlyOwner { AdminInterface admin = AdminInterface(derivative); admin.remargin(); } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable) { // Ensure that the caller has been registered with the Oracle before processing the request. require(registry.isDerivativeRegistered(msg.sender)); require(supportedIdentifiers[identifier]); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint time) external view returns (int price) { // Ensure that the caller has been registered with the Oracle before processing the request. require(registry.isDerivativeRegistered(msg.sender)); require(supportedIdentifiers[identifier]); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view onlyOwner returns (QueryPoint[] memory queryPoints) { return requestedPrices; } // Whether the oracle provides verified prices for the provided identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported) { return supportedIdentifiers[identifier]; } event AddSupportedIdentifier(bytes32 indexed identifier); }
Calls emergencyShutdown() on the provided derivative.
function callEmergencyShutdown(address derivative) external onlyOwner { AdminInterface admin = AdminInterface(derivative); admin.emergencyShutdown(); }
1,057,708
//"SPDX-License-Identifier: UNLICENSED" pragma solidity ^0.6.0; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol"; contract Tokenview is ERC20{ modifier onlyOwner(){ require(msg.sender == owner); _; } uint256 public pricepertoken = 25000000000000; uint256 public supplycap = 90000000000000000000000000; address public owner; bool public paused; /** * @param o set as owner admin **/ constructor(address o) public ERC20("Tokenview", "TKNV") { _mint(o, 50000000000000000000000000); owner = o; } //User /** * @dev 1 * 10^18 represents 1 TKNV * */ function purchaseTokens() external payable { require(!paused, 'Purchasing is currently disabled'); require(msg.value >= pricepertoken, "Insufficient payment, you must buy at least 1 token"); _transfer(owner, msg.sender, msg.value/pricepertoken*1000000000000000000); } //Admin /** *@param amt the number of tokens to mint **/ function mintTokens(uint256 amt) public onlyOwner { require(totalSupply() + amt <= supplycap, 'Exceeded supply cap'); _mint(msg.sender, amt); } /** * @dev burns tokens from owner * @param amt the number of tokens to burn **/ function burnTokens(uint256 amt) public onlyOwner { _burn(owner, amt); } /** * @param newprice price per token to set **/ function setPrice(uint256 newprice) public onlyOwner { pricepertoken = newprice; } /** * @dev turns paused on/off **/ function switchPause() public onlyOwner{ paused = !paused; } /** * @dev withdraws all eth from contract **/ function foundationWithdraw() public onlyOwner{ msg.sender.transfer(address(this).balance); } }
User 1 10^18 represents 1 TKNV /
function purchaseTokens() external payable { require(!paused, 'Purchasing is currently disabled'); require(msg.value >= pricepertoken, "Insufficient payment, you must buy at least 1 token"); _transfer(owner, msg.sender, msg.value/pricepertoken*1000000000000000000); }
2,526,460
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/ERC20.sol
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 returns (bool) { address owner = msg.sender; uint256 currentAllowance = allowance(owner, spender); require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(owner, spender, currentAllowance - subtractedValue); return true; }
2,595,174
pragma solidity ^0.5.11; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ERC721Collection.sol"; import "./interfaces/Factory.sol"; contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract ERC721CollectionFactory is Ownable, Factory { using SafeMath for uint256; string public name; string public symbol; string public baseURI; ProxyRegistry public proxyRegistry; ERC721Collection public erc721Collection; event BaseURI(string _oldBaseURI, string _newBaseURI); event Allowed(address indexed _oldAllowed, address indexed _newAllowed); /** * @dev Constructor of the contract. * @notice that 0xa5409ec958c83c3f309868babaca7c86dcb077c1 is the contract address for _proxyRegistryAddress at mainnet. * @param _name - name of the contract * @param _symbol - symbol of the contract * @param _baseURI - base URI for token URIs * @param _proxyRegistry - Address of the ProxyRegistry using at OpenSea * @param _erc721Collection - Address of the collection */ constructor( string memory _name, string memory _symbol, string memory _baseURI, ProxyRegistry _proxyRegistry, ERC721Collection _erc721Collection ) public { name = _name; symbol = _symbol; proxyRegistry = _proxyRegistry; erc721Collection = _erc721Collection; setBaseURI(_baseURI); } modifier onlyAllowed() { require(address(proxyRegistry.proxies(owner())) == msg.sender, "Only `allowed` proxy can issue tokens"); _; } /** * @dev Mints asset(s) in accordance to a specific address with a particular "option". This should be * callable only by the contract owner or the owner's Wyvern Proxy (later universal login will solve this). * Options should also be delineated 0 - (numOptions() - 1) for convenient indexing. * @param _optionId the option id * @param _toAddress address of the future owner of the asset(s) */ function mint(uint256 _optionId, address _toAddress) public onlyAllowed { require(canMint(_optionId), "Exhausted wearable"); string memory wearable = _wearableByOptionId(_optionId); erc721Collection.issueToken(_toAddress, wearable); } /** * @dev Set Base URI. * @param _baseURI - base URI for token URIs */ function setBaseURI(string memory _baseURI) public onlyOwner { emit BaseURI(baseURI, _baseURI); baseURI = _baseURI; } /** * @dev Returns whether the option ID can be minted. Can return false if the developer wishes to * restrict a total supply per option ID (or overall). * @param _optionId the option id * @return whether an option can be minted */ function canMint(uint256 _optionId) public view returns (bool) { return balanceOf(_optionId) > 0; } /** * @dev Check if support factory interface. * @return always true */ function supportsFactoryInterface() public view returns (bool) { return true; } /** * @dev Return the number of options the factory supports. * @return supported options count */ function numOptions() public view returns (uint256) { return erc721Collection.wearablesCount(); } /** * @dev Returns an URI for a given option ID. * Throws if the option ID does not exist. May return an empty string. * @param _optionId - uint256 ID of the token queried * @return token URI */ function balanceOf(uint256 _optionId) public view returns (uint256) { string memory wearable = _wearableByOptionId(_optionId); bytes32 wearableKey = erc721Collection.getWearableKey(wearable); uint256 issued = erc721Collection.issued(wearableKey); uint256 maxIssuance = erc721Collection.maxIssuance(wearableKey); return maxIssuance.sub(issued); } /** * @dev Returns an URI for a given option ID. * Throws if the option ID does not exist. May return an empty string. * @param _optionId - uint256 ID of the token queried * @return token URI */ function tokenURI(uint256 _optionId) public view returns (string memory) { string memory wearable = _wearableByOptionId(_optionId); return string(abi.encodePacked(baseURI, wearable)); } /** * @dev Get the proxy address used at OpenSea. * @notice that this address should be used at setAllowed method * to allow OpenSea to mint tokens. * OpenSea uses the Wyvern Protocol https://docs.opensea.io/docs/opensea-partners-program * @param _operator - Address allowed to issue tokens */ // Should be used to return the address to be set as setAllowed function proxies(address _operator) public view returns (address) { return address(proxyRegistry.proxies(_operator)); } /** * Hack to get things to work automatically on OpenSea. * Use transferFrom so the frontend doesn't have to worry about different method names. */ function transferFrom(address /*_from*/, address _to, uint256 _tokenId) public { mint(_tokenId, _to); } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { if (owner() == _owner && _owner == _operator) { return true; } if (owner() == _owner && address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return false; } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function ownerOf(uint256 /*_tokenId*/) public view returns (address _owner) { return owner(); } function _wearableByOptionId(uint256 _optionId) internal view returns (string memory){ /* solium-disable-next-line */ (bool success, bytes memory data) = address(erc721Collection).staticcall( abi.encodeWithSelector( erc721Collection.wearables.selector, _optionId ) ); require(success, "Invalid wearable"); return abi.decode(data, (string)); } }
Hack to get things to work automatically on OpenSea. Use isApprovedForAll so the frontend doesn't have to worry about different method names./
function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { if (owner() == _owner && _owner == _operator) { return true; } if (owner() == _owner && address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return false; }
1,087,500
./full_match/1/0xc62993f7a8d50CFF5e49CC2783abFc9BbE22821e/sources/newtoken.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("WEN MOON", "MOON") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 20; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 30; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x599Ea0311a8cA7F48371D2c786cE4e243a2B52d2); devWallet = address(0x599Ea0311a8cA7F48371D2c786cE4e243a2B52d2); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,464,570
./full_match/42/0xC5813Aa4f8105B63E8f5F25b90d446fc3deA635c/sources/UnitTest/PreachersCompFiLqdtKyberSwapKovanAL.sol
KyberSwap functions/ Swap from srcToken to destToken (including ether) If the source token is not ETH (ie. an ERC20 token), the user is required to first call the ERC20 approve function to give an allowance to the smart contract executing the transferFrom function. mitigate ERC20 Approve front-running attack, by initially setting allowance to 0 set the spender's token allowance to srcQty
function executeKyberSwap( address SrcToken, uint256 srcQty, address DestToken, address payable destAddress, uint256 maxDestAmount ) public returns ( uint256 ) { emit KyberSwapETH( destAddress, SrcToken, srcQty, DestToken, maxDestAmount); ISimpleKyberProxy cSimpleKyberProxy = ISimpleKyberProxy( kKyberNetworkProxy ); IKyberNetworkProxy cKyberProxy = IKyberNetworkProxy( kKyberNetworkProxy ); ERC20 cSrcToken = ERC20(SrcToken); ERC20 cDestToken = ERC20(DestToken); uint256 destAmount = 0; ( uint256 minConversionRate, uint256 worstRate ) = cKyberProxy.getExpectedRate( cSrcToken, cDestToken, srcQty ); emit ExpectedRate( minConversionRate, worstRate ); if (SrcToken == kETH) { require(cSrcToken.approve(address(this), 0), "approval to 0 failed"); require(cSrcToken.approve(address(this), srcQty), "approval to srcQty failed"); emit ApprovedSrcSwap( SrcToken, srcQty ); if (DestToken == kETH) { destAmount = cSimpleKyberProxy.swapTokenToEther(cSrcToken, srcQty, minConversionRate); destAmount = cSimpleKyberProxy.swapTokenToToken( cSrcToken, srcQty, cDestToken, minConversionRate); } } emit KyberSwapped( address(cSrcToken), srcQty, address(cDestToken), destAmount, minConversionRate ); return destAmount; } event ChangedOwner( address payable owner, address payable newOwner ); event Liquidated( address account, address token, uint256 amount ); event PassThru( uint256 liquidateampount ); event Withdrawn( address token, uint256 amount ); event Borrowed( address tokenborrowed, uint256 amount ); event Received( address, uint ); event KyberSwapped( address fromtoken, uint256 fromamount, address totoken, uint256 toamount, uint256 minConversionRate ); event MinKyberConversionRate(uint256 srcQty, uint256 minConversionRate ); event KyberSwapETH( address payable destAddress, address SrcToken, uint256 srcQty, address DestToken, uint256 maxDestAmount ); event ApprovedSrcSwap( address SrcToken, uint256 srcQty ); event ExpectedRate( uint256 minConversionRate, uint256 worstRate );
9,590,071
/** *Submitted for verification at Etherscan.io on 2021-07-28 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs 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} } struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IAaveDistributionManager interface IAaveDistributionManager { event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated( address indexed user, address indexed asset, uint256 index ); event DistributionEndUpdated(uint256 newDistributionEnd); /** * @dev Sets the end date for the distribution * @param distributionEnd The end date timestamp **/ function setDistributionEnd(uint256 distributionEnd) external; /** * @dev Gets the end date for the distribution * @return The end of the distribution **/ function getDistributionEnd() external view returns (uint256); /** * @dev for backwards compatibility with the previous DistributionManager used * @return The end of the distribution **/ function DISTRIBUTION_END() external view returns (uint256); /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) external view returns (uint256); /** * @dev Returns the configuration of the distribution for a certain asset * @param asset The address of the reference asset of the distribution * @return The asset index, the emission per second and the last updated timestamp **/ function getAssetData(address asset) external view returns ( uint256, uint256, uint256 ); } // Part: ILendingPoolAddressesProvider /** * @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 ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); 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 getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; 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; } // Part: IPriceOracle interface IPriceOracle { function getAssetPrice(address _asset) external view returns (uint256); } // Part: IStakedAave interface IStakedAave { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; } // Part: IUniswapV3SwapCallback /// @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; } // 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: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: IAaveIncentivesController interface IAaveIncentivesController is IAaveDistributionManager { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets( address[] calldata assets, uint256[] calldata emissionsPerSecond ) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); } // Part: ILendingPool interface ILendingPool { /** * @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 * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @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 * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @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 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 (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // Part: ISwapRouter /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // 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 { 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 is 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 { } } // 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: yearn/[email protected]/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 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); // 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 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: yearn/[email protected]/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; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @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 modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } 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()); want.safeApprove(_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 } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @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. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } 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) want.safeTransfer(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); want.safeTransfer(_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"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; ILendingPoolAddressesProvider public constant ADDRESS_PROVIDER = ILendingPoolAddressesProvider( 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5 ); IERC20 public immutable aToken; IERC20 public immutable vToken; ILendingPool public immutable LENDING_POOL; uint256 public immutable DECIMALS; // For toETH conversion // stkAAVE IERC20 public constant reward = IERC20(0x4da27a545c0c5B758a6BA100e3a049001de870f5); // Token we farm and swap to want / aToken // Hardhcoded from the Liquidity Mining docs: https://docs.aave.com/developers/guides/liquidity-mining IAaveIncentivesController public constant INCENTIVES_CONTROLLER = IAaveIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5); // For Swapping ISwapRouter public constant ROUTER = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); IERC20 public constant AAVE_TOKEN = IERC20(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); IERC20 public constant WETH_TOKEN = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // Min Price we tollerate when swapping from stkAAVE to AAVE uint256 public minStkAAVEPRice = 9500; // 95% uint256 public minAAVEToWantPrice = 8000; // 80% // Seems like Oracle is slightly off // Should we harvest before prepareMigration bool public harvestBeforeMigrate = true; // Should we ensure the swap will be within slippage params before performing it during normal harvest? bool public checkSlippageOnHarvest = true; // Leverage uint256 public constant MAX_BPS = 10000; uint256 public minHealth = 1080000000000000000; // 1.08 with 18 decimals this is slighly above 70% tvl uint256 public minRebalanceAmount = 50000000; // 0.5 should be changed based on decimals (btc has 8) constructor(address _vault) public BaseStrategy(_vault) { // You can set these parameters on deployment to whatever you want maxReportDelay = 6300; profitFactor = 100; debtThreshold = 0; // Get lending Pool ILendingPool lendingPool = ILendingPool(ADDRESS_PROVIDER.getLendingPool()); // Set lending pool as immutable LENDING_POOL = lendingPool; // Get Tokens Addresses DataTypes.ReserveData memory data = lendingPool.getReserveData(address(want)); // Get aToken aToken = IERC20(data.aTokenAddress); // Get vToken vToken = IERC20(data.variableDebtTokenAddress); // Get Decimals DECIMALS = ERC20(address(want)).decimals(); want.safeApprove(address(lendingPool), type(uint256).max); reward.safeApprove(address(ROUTER), type(uint256).max); AAVE_TOKEN.safeApprove(address(ROUTER), type(uint256).max); } function setMinHealth(uint256 newMinHealth) external onlyKeepers { require(newMinHealth >= 1000000000000000000, "Need higher health"); minHealth = newMinHealth; } function setHarvestBeforeMigrate(bool newHarvestBeforeMigrate) external onlyKeepers { harvestBeforeMigrate = newHarvestBeforeMigrate; } function setCheckSlippageOnHarvest(bool newCheckSlippageOnHarvest) external onlyKeepers { checkSlippageOnHarvest = newCheckSlippageOnHarvest; } function setMinStkAAVEPRice(uint256 newMinStkAAVEPRice) external onlyKeepers { require(newMinStkAAVEPRice >= 0 && newMinStkAAVEPRice <= MAX_BPS); minStkAAVEPRice = newMinStkAAVEPRice; } function setMinPrice(uint256 newMinAAVEToWantPrice) external onlyKeepers { require(newMinAAVEToWantPrice >= 0 && newMinAAVEToWantPrice <= MAX_BPS); minAAVEToWantPrice = newMinAAVEToWantPrice; } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return "Strategy-Levered-AAVE-wBTC"; } function estimatedTotalAssets() public view override returns (uint256) { // Balance of want + balance in AAVE uint256 liquidBalance = want.balanceOf(address(this)).add(deposited()).sub(borrowed()); // Return balance + reward return liquidBalance.add(valueOfRewards()); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // NOTE: This means that if we are paying back we just deleverage // While if we are not paying back, we are harvesting rewards if (_debtOutstanding > 0) { // Withdraw and Repay uint256 toWithdraw = _debtOutstanding; // Get it all out _divestFromAAVE(); // Get rewards _claimRewardsAndGetMoreWant(); // Repay debt uint256 maxRepay = want.balanceOf(address(this)); if (_debtOutstanding > maxRepay) { // we can't pay all, means we lost some _loss = _debtOutstanding.sub(maxRepay); _debtPayment = maxRepay; } else { // We can pay all, let's do it _debtPayment = toWithdraw; } } else { // Do normal Harvest _debtPayment = 0; // Get current amount of want // used to estimate profit uint256 beforeBalance = want.balanceOf(address(this)); // Claim stkAAVE -> swap into want _claimRewardsAndGetMoreWant(); (uint256 earned, uint256 lost) = _repayAAVEBorrow(beforeBalance); _profit = earned; _loss = lost; } } function _repayAAVEBorrow(uint256 beforeBalance) internal returns (uint256 _profit, uint256 _loss) { uint256 afterSwapBalance = want.balanceOf(address(this)); uint256 wantFromSwap = afterSwapBalance.sub(beforeBalance); // Calculate Gain from AAVE interest // NOTE: This should never happen as we take more debt than we earn uint256 currentWantInAave = deposited().sub(borrowed()); uint256 initialDeposit = vault.strategies(address(this)).totalDebt; if (currentWantInAave > initialDeposit) { uint256 interestProfit = currentWantInAave.sub(initialDeposit); LENDING_POOL.withdraw(address(want), interestProfit, address(this)); // Withdraw interest of aToken so that now we have exactly the same amount } uint256 afterBalance = want.balanceOf(address(this)); uint256 wantEarned = afterBalance.sub(beforeBalance); // Earned before repaying debt // Pay off any debt // Debt is equal to negative of canBorrow uint256 toRepay = debtBelowHealth(); if (toRepay > wantEarned) { // We lost some money // Repay all we can, rest is loss LENDING_POOL.repay(address(want), wantEarned, 2, address(this)); _loss = toRepay.sub(wantEarned); // Notice that once the strats starts loosing funds here, you should probably retire it as it's not profitable } else { // We made money or are even // Let's repay the debtBelowHealth uint256 repaid = toRepay; _profit = wantEarned.sub(repaid); if (repaid > 0) { LENDING_POOL.repay(address(want), repaid, 2, address(this)); } } } function adjustPosition(uint256 _debtOutstanding) internal override { // TODO: Do something to invest excess `want` tokens (from the Vault) into your positions // NOTE: Try to adjust positions so that `_debtOutstanding` can be freed up on *next* harvest (not immediately) uint256 wantAvailable = want.balanceOf(address(this)); if (wantAvailable > _debtOutstanding) { uint256 toDeposit = wantAvailable.sub(_debtOutstanding); LENDING_POOL.deposit(address(want), toDeposit, address(this), 0); // Lever up _invest(); } } function balanceOfRewards() public view returns (uint256) { // Get rewards address[] memory assets = new address[](2); assets[0] = address(aToken); assets[1] = address(vToken); uint256 totalRewards = INCENTIVES_CONTROLLER.getRewardsBalance(assets, address(this)); return totalRewards; } function valueOfAAVEToWant(uint256 aaveAmount) public view returns (uint256) { return ethToWant(AAVEToETH(aaveAmount)); } function valueOfRewards() public view returns (uint256) { return valueOfAAVEToWant(balanceOfRewards()); } // Get stkAAVE function _claimRewards() internal { // Get rewards address[] memory assets = new address[](2); assets[0] = address(aToken); assets[1] = address(vToken); // Get Rewards, withdraw all INCENTIVES_CONTROLLER.claimRewards( assets, type(uint256).max, address(this) ); } function _fromSTKAAVEToAAVE(uint256 rewardsAmount, uint256 minOut) internal { // Swap Rewards in UNIV3 // NOTE: Unoptimized, can be frontrun and most importantly this pool is low liquidity ISwapRouter.ExactInputSingleParams memory fromRewardToAAVEParams = ISwapRouter.ExactInputSingleParams( address(reward), address(AAVE_TOKEN), 10000, address(this), now, rewardsAmount, // wei minOut, 0 ); ROUTER.exactInputSingle(fromRewardToAAVEParams); } function _fromAAVEToWant(uint256 amountIn, uint256 minOut) internal { // We now have AAVE tokens, let's get want bytes memory path = abi.encodePacked( address(AAVE_TOKEN), uint24(10000), address(WETH_TOKEN), uint24(10000), address(want) ); ISwapRouter.ExactInputParams memory fromAAVETowBTCParams = ISwapRouter.ExactInputParams( path, address(this), now, amountIn, minOut ); ROUTER.exactInput(fromAAVETowBTCParams); } function _claimRewardsAndGetMoreWant() internal { _claimRewards(); uint256 rewardsAmount = reward.balanceOf(address(this)); if (rewardsAmount == 0) { return; } // Specify a min out uint256 minAAVEOut = rewardsAmount.mul(minStkAAVEPRice).div(MAX_BPS); _fromSTKAAVEToAAVE(rewardsAmount, minAAVEOut); uint256 aaveToSwap = AAVE_TOKEN.balanceOf(address(this)); uint256 minWantOut = 0; if (checkSlippageOnHarvest) { minWantOut = valueOfAAVEToWant(aaveToSwap) .mul(minAAVEToWantPrice) .div(MAX_BPS); } _fromAAVEToWant(aaveToSwap, minWantOut); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // TODO: Do stuff here to free up to `_amountNeeded` from all positions back into `want` // NOTE: Maintain invariant `want.balanceOf(this) >= _liquidatedAmount` // NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded` // Lever Down _divestFromAAVE(); uint256 totalAssets = want.balanceOf(address(this)); if (_amountNeeded > totalAssets) { _liquidatedAmount = totalAssets; _loss = _amountNeeded.sub(totalAssets); } else { _liquidatedAmount = _amountNeeded; } } // Withdraw all from AAVE Pool function liquidateAllPositions() internal override returns (uint256) { // Repay all debt and divest _divestFromAAVE(); // Get rewards before leaving _claimRewardsAndGetMoreWant(); // Return amount freed return want.balanceOf(address(this)); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // TODO: Transfer any non-`want` tokens to the new strategy // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one // This is gone if we use upgradeable //Divest all _divestFromAAVE(); if (harvestBeforeMigrate) { // Harvest rewards one last time _claimRewardsAndGetMoreWant(); } // Just in case we don't fully liquidate to want if (aToken.balanceOf(address(this)) > 0) { aToken.safeTransfer(_newStrategy, aToken.balanceOf(address(this))); } if (reward.balanceOf(address(this)) > 0) { reward.safeTransfer(_newStrategy, reward.balanceOf(address(this))); } } // 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 override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = address(aToken); protected[1] = address(reward); 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 virtual override returns (uint256) { address priceOracle = ADDRESS_PROVIDER.getPriceOracle(); uint256 priceInEth = IPriceOracle(priceOracle).getAssetPrice(address(want)); // Opposite of priceInEth // Multiply first to keep rounding uint256 priceInWant = _amtInWei.mul(10**DECIMALS).div(priceInEth); return priceInWant; } function AAVEToETH(uint256 _amt) public view returns (uint256) { address priceOracle = ADDRESS_PROVIDER.getPriceOracle(); uint256 priceInEth = IPriceOracle(priceOracle).getAssetPrice(address(AAVE_TOKEN)); // Price in ETH // AMT * Price in ETH / Decimals uint256 aaveToEth = _amt.mul(priceInEth).div(10**18); return aaveToEth; } /* Leverage functions */ function deposited() public view returns (uint256) { return aToken.balanceOf(address(this)); } function borrowed() public view returns (uint256) { return vToken.balanceOf(address(this)); } // What should we repay? function debtBelowHealth() public view returns (uint256) { ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) = LENDING_POOL.getUserAccountData(address(this)); // How much did we go off of minHealth? //NOTE: We always borrow as much as we can uint256 maxBorrow = deposited().mul(ltv).div(MAX_BPS); if (healthFactor < minHealth && borrowed() > maxBorrow) { uint256 maxValue = borrowed().sub(maxBorrow); return maxValue; } return 0; } // NOTE: We always borrow max, no fucks given function canBorrow() public view returns (uint256) { ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) = LENDING_POOL.getUserAccountData(address(this)); if (healthFactor > minHealth) { // Amount = deposited * ltv - borrowed // Div MAX_BPS because because ltv / maxbps is the percent uint256 maxValue = deposited().mul(ltv).div(MAX_BPS).sub(borrowed()); // Don't borrow if it's dust, save gas if (maxValue < minRebalanceAmount) { return 0; } return maxValue; } return 0; } function _invest() internal { // Loop on it until it's properly done uint256 max_iterations = 5; for (uint256 i = 0; i < max_iterations; i++) { uint256 toBorrow = canBorrow(); if (toBorrow > 0) { LENDING_POOL.borrow( address(want), toBorrow, 2, 0, address(this) ); LENDING_POOL.deposit(address(want), toBorrow, address(this), 0); } else { break; } } } // Divest all from AAVE, awful gas, but hey, it works function _divestFromAAVE() internal { uint256 repayAmount = canRepay(); // The "unsafe" (below target health) you can withdraw // Loop to withdraw until you have the amount you need while (repayAmount != uint256(-1)) { _withdrawStepFromAAVE(repayAmount); repayAmount = canRepay(); } if (deposited() > 0) { // Withdraw the rest here LENDING_POOL.withdraw( address(want), type(uint256).max, address(this) ); } } // Withdraw and Repay AAVE Debt function _withdrawStepFromAAVE(uint256 canRepay) internal { if (canRepay > 0) { //Repay this step LENDING_POOL.withdraw(address(want), canRepay, address(this)); LENDING_POOL.repay(address(want), canRepay, 2, address(this)); } } // returns 95% of the collateral we can withdraw from aave, used to loop and repay debts function canRepay() public view returns (uint256) { ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) = LENDING_POOL.getUserAccountData(address(this)); uint256 aBalance = deposited(); uint256 vBalance = borrowed(); if (vBalance == 0) { return uint256(-1); //You have repaid all } uint256 diff = aBalance.sub(vBalance.mul(10000).div(currentLiquidationThreshold)); uint256 inWant = diff.mul(95).div(100); // Take 95% just to be safe return inWant; } /** Manual Functions */ /** Leverage Manual Functions */ // Emergency function to immediately deleverage to 0 function manualDivestFromAAVE() public onlyVaultManagers { _divestFromAAVE(); } // Manually perform 5 loops to lever up // Safe because it's capped by canBorrow function manualLeverUp() public onlyVaultManagers { _invest(); } // Emergency function that we can use to deleverage manually if something is broken // If something goes wrong, just try smaller and smaller can repay amounts function manualWithdrawStepFromAAVE(uint256 toRepay) public onlyVaultManagers { _withdrawStepFromAAVE(toRepay); } // Take some funds from manager and use them to repay // Useful if you ever go below 1 HF and somehow you didn't get liquidated function manualRepayFromManager(uint256 toRepay) public onlyVaultManagers { want.safeTransferFrom(msg.sender, address(this), toRepay); LENDING_POOL.repay(address(want), toRepay, 2, address(this)); } /** DCA Manual Functions */ // Get the rewards function manualClaimRewards() public onlyVaultManagers { _claimRewards(); } // Initiate 10 days cooldown period manually // You can use this if you believe V3 Pool is too illiquid function manualCooldownRewards() public onlyVaultManagers { IStakedAave stkAAVE = IStakedAave(address(reward)); stkAAVE.claimRewards(address(this), type(uint256).max); stkAAVE.cooldown(); } // Manually redeem rewards, claiming AAVE // You can use this if you believe V3 Pool is too illiquid function manualRedeemRewards() public onlyVaultManagers { IStakedAave stkAAVE = IStakedAave(address(reward)); stkAAVE.claimRewards(address(this), type(uint256).max); stkAAVE.redeem(address(this), type(uint256).max); } // Swap from stkAAVE to AAVE ///@param amountToSwap Amount of stkAAVE to Swap, NOTE: You have to calculate the amount!! ///@param multiplierInWei pricePerToken including slippage, will be divided by 10 ** 18 function manualSwapFromStkAAVEToAAVE( uint256 amountToSwap, uint256 multiplierInWei ) public onlyVaultManagers { uint256 amountOutMinimum = amountToSwap.mul(multiplierInWei).div(10**18); _fromSTKAAVEToAAVE(amountToSwap, amountOutMinimum); } // Swap from AAVE to Want ///@param amountToSwap Amount of AAVE to Swap, NOTE: You have to calculate the amount!! ///@param multiplierInWei pricePerToken including slippage, will be divided by 10 ** 18 function manualSwapFromAAVEToWant( uint256 amountToSwap, uint256 multiplierInWei ) public onlyVaultManagers { uint256 amountOutMinimum = amountToSwap.mul(multiplierInWei).div(10**18); _fromAAVEToWant(amountToSwap, amountOutMinimum); } }
Divest all from AAVE, awful gas, but hey, it works Loop to withdraw until you have the amount you need Withdraw the rest here
function _divestFromAAVE() internal { while (repayAmount != uint256(-1)) { _withdrawStepFromAAVE(repayAmount); repayAmount = canRepay(); } if (deposited() > 0) { LENDING_POOL.withdraw( address(want), type(uint256).max, address(this) ); } }
6,544,866
pragma solidity >=0.4.21 <0.6.0; pragma experimental ABIEncoderV2; contract BuyTickets{ address payable public owner = 0x4190C332e7D40bF2E7A370Bbc836F5b8832CB326; //平台帳號,永遠固定 uint buyers = 0; address[] public buyerAccounts; uint price; uint public countConfirms = 0; //auto pay when all buyers confirm constructor() public{ /* owner = msg.sender; */ // price = 1 ether; } struct Buyer { string email; bool status; } mapping (address => uint) balance; mapping (address => Buyer) theBuyer; // event buyerRegistered(address email); function setBuyer(address[] memory arr, string[] memory email, bool[] memory status) public { for(uint i = 0; i < arr.length ; i++){ theBuyer[arr[i]].email = email[i]; theBuyer[arr[i]].status = status[i]; buyers++; buyerAccounts.push(arr[i]) - 1; } buyers = arr.length; // emit buyerRegistered(buyer.email); } //confirm(): change status to true, and put in ether function confirm(uint _amount) public payable{ /* require() */ // require(msg.value == price); //making sure they are paying the right amount require(includes(buyerAccounts, msg.sender)); //making sure the account calling confirm is in the array require(theBuyer[msg.sender].status != true); theBuyer[msg.sender].status = true; //set buyer status to true balance[msg.sender] += msg.value; //remember how many a buyer paid countConfirms++; if(countConfirms == buyerAccounts.length){ //if all the buyers had confirm, pay automatically buyTickets(buyers * _amount); } } // cancel function cancel() public payable{ // require(theBuyer[msg.sender].status == true); //make sure the buyer calling cancel was true theBuyer[msg.sender].status = false; //change buyer status to false countConfirms--; balance[msg.sender] -= price; msg.sender.transfer(price); //transfer money back to buyer } //buyTickets(): transfer ether to owner function buyTickets(uint _amount) public payable{ require(checkIfTrue()); owner.transfer(1 ether * _amount); //transfer ether to the contract owner } //to make sure the account calling confirm() is in the array function includes(address[] memory arr, address find) public pure returns(bool){ uint count = 0; for(uint i = 0; i < arr.length; i++){ if(arr[i] == find){ count++; } } if(count > 0){ return true; } else{ return false; } } //check if all accounts status is true function checkIfTrue() public view returns(bool){ uint flag = 0; for(uint j = 0; j< buyerAccounts.length -1; j++){ if(theBuyer[buyerAccounts[j]].status == true){ flag++; } } if(flag == buyerAccounts.length -1){ return true; } else{ return false; } } function checkDuplicate(address arr) public view returns(bool){ if(buyerAccounts.length == 0){ return true; }else{ for(uint s = 0; s <= buyerAccounts.length -1 ; s++){ /* buyerAccounts[s] == arr ? false: true; */ if(buyerAccounts[s] == arr){ return false; } /* else{ return true; } */ } } /* buyerAccounts.forEach( function(element) { if(element != arr){ check = true; } }) */ return true; } } /** console script var accounts; web3.eth.getAccounts(function(err, res){accounts = res}); var account1 = accounts[1] ... Eticket.deployed().then(inst => { test = inst }) test.setBuyer(account1, 'buyer1', false) ... test.confirm({from: account1, value: web3.utils.toWei('1', 'ether')}); ... **/
confirm(): change status to true, and put in ether require(msg.value == price); making sure they are paying the right amount
function confirm(uint _amount) public payable{ require(theBuyer[msg.sender].status != true); countConfirms++; buyTickets(buyers * _amount); }
7,302,728
pragma solidity ^0.4.8; contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender == owner) _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) owner = newOwner; } } contract TokenSpender { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract PullPayment { mapping(address => uint) public payments; event RefundETH(address to, uint value); // store sent amount as credit to be pulled, called by payer function asyncSend(address dest, uint amount) internal { payments[dest] += amount; } // withdraw accumulated balance, called by payee function withdrawPayments() { address payee = msg.sender; uint payment = payments[payee]; if (payment == 0) { throw; } if (this.balance < payment) { throw; } payments[payee] = 0; if (!payee.send(payment)) { throw; } RefundETH(payee,payment); } } contract Pausable is Ownable { bool public stopped; modifier stopInEmergency { if (stopped) { throw; } _; } modifier onlyInEmergency { if (!stopped) { throw; } _; } // called by the owner on emergency, triggers stopped state function emergencyStop() external onlyOwner { stopped = true; } // called by the owner on end of emergency, returns to normal state function release() external onlyOwner onlyInEmergency { stopped = false; } } contract RLC is ERC20, SafeMath, Ownable { /* Public variables of the token */ string public name; //fancy name string public symbol; uint8 public decimals; //How many decimals to show. string public version = 'v0.1'; uint public initialSupply; uint public totalSupply; bool public locked; //uint public unlockBlock; mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; // lock transfer during the ICO modifier onlyUnlocked() { if (msg.sender != owner && locked) throw; _; } /* * The RLC Token created with the time at which the crowdsale end */ function RLC() { // lock the transfer function during the crowdsale locked = true; //unlockBlock= now + 45 days; // (testnet) - for mainnet put the block number initialSupply = 87000000000000000; totalSupply = initialSupply; balances[msg.sender] = initialSupply;// Give the creator all initial tokens name = 'iEx.ec Network Token'; // Set the name for display purposes symbol = 'RLC'; // Set the symbol for display purposes decimals = 9; // Amount of decimals for display purposes } function unlock() onlyOwner { locked = false; } function burn(uint256 _value) returns (bool){ balances[msg.sender] = safeSub(balances[msg.sender], _value) ; totalSupply = safeSub(totalSupply, _value); Transfer(msg.sender, 0x0, _value); return true; } function transfer(address _to, uint _value) onlyUnlocked returns (bool) { balances[msg.sender] = safeSub(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) onlyUnlocked returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* Approve and then comunicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData){ TokenSpender spender = TokenSpender(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); } } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract Crowdsale is SafeMath, PullPayment, Pausable { struct Backer { uint weiReceived; // Amount of ETH given string btc_address; //store the btc address for full traceability uint satoshiReceived; // Amount of BTC given uint rlcSent; } RLC public rlc; // RLC contract reference address public owner; // Contract owner (iEx.ec team) address public multisigETH; // Multisig contract that will receive the ETH address public BTCproxy; // address of the BTC Proxy uint public RLCPerETH; // Number of RLC per ETH uint public RLCPerSATOSHI; // Number of RLC per SATOSHI uint public ETHReceived; // Number of ETH received uint public BTCReceived; // Number of BTC received uint public RLCSentToETH; // Number of RLC sent to ETH contributors uint public RLCSentToBTC; // Number of RLC sent to BTC contributors uint public startBlock; // Crowdsale start block uint public endBlock; // Crowdsale end block uint public minCap; // Minimum number of RLC to sell uint public maxCap; // Maximum number of RLC to sell bool public maxCapReached; // Max cap has been reached uint public minInvestETH; // Minimum amount to invest uint public minInvestBTC; // Minimum amount to invest bool public crowdsaleClosed;// Is crowdsale still on going address public bounty; // address at which the bounty RLC will be sent address public reserve; // address at which the contingency reserve will be sent address public team; // address at which the team RLC will be sent uint public rlc_bounty; // amount of bounties RLC uint public rlc_reserve; // amount of the contingency reserve uint public rlc_team; // amount of the team RLC mapping(address => Backer) public backers; //backersETH indexed by their ETH address modifier onlyBy(address a){ if (msg.sender != a) throw; _; } modifier minCapNotReached() { if ((now<endBlock) || RLCSentToETH + RLCSentToBTC >= minCap ) throw; _; } modifier respectTimeFrame() { if ((now < startBlock) || (now > endBlock )) throw; _; } /* * Event */ event ReceivedETH(address addr, uint value); event ReceivedBTC(address addr, string from, uint value, string txid); event RefundBTC(string to, uint value); event Logs(address indexed from, uint amount, string value); /* * Constructor */ //function Crowdsale() { function Crowdsale() { owner = msg.sender; BTCproxy = 0x75c6cceb1a33f177369053f8a0e840de96b4ed0e; rlc = RLC(0x607f4c5bb672230e8672085532f7e901544a7375); multisigETH = 0xAe307e3871E5A321c0559FBf0233A38c937B826A; team = 0xd65380D773208a6Aa49472Bf55186b855B393298; reserve = 0x24F6b37770C6067D05ACc2aD2C42d1Bafde95d48; bounty = 0x8226a24dA0870Fb8A128E4Fc15228a9c4a5baC29; RLCSentToETH = 0; RLCSentToBTC = 0; minInvestETH = 1 ether; minInvestBTC = 5000000; // approx 50 USD or 0.05000000 BTC startBlock = 0 ; // should wait for the call of the function start endBlock = 0; // should wait for the call of the function start RLCPerETH = 200000000000; // will be update every 10min based on the kraken ETHBTC RLCPerSATOSHI = 50000; // 5000 RLC par BTC == 50,000 RLC per satoshi minCap=12000000000000000; maxCap=60000000000000000; rlc_bounty=1700000000000000; // max 6000000 RLC rlc_reserve=1700000000000000; // max 6000000 RLC rlc_team=12000000000000000; } /* * The fallback function corresponds to a donation in ETH */ function() payable { if (now > endBlock) throw; receiveETH(msg.sender); } /* * To call to start the crowdsale */ function start() onlyBy(owner) { startBlock = now ; endBlock = now + 30 days; } /* * Receives a donation in ETH */ function receiveETH(address beneficiary) internal stopInEmergency respectTimeFrame { if (msg.value < minInvestETH) throw; //don't accept funding under a predefined threshold uint rlcToSend = bonus(safeMul(msg.value,RLCPerETH)/(1 ether)); //compute the number of RLC to send if (safeAdd(rlcToSend, safeAdd(RLCSentToETH, RLCSentToBTC)) > maxCap) throw; Backer backer = backers[beneficiary]; if (!rlc.transfer(beneficiary, rlcToSend)) throw; // Do the RLC transfer right now backer.rlcSent = safeAdd(backer.rlcSent, rlcToSend); backer.weiReceived = safeAdd(backer.weiReceived, msg.value); // Update the total wei collected during the crowdfunding for this backer ETHReceived = safeAdd(ETHReceived, msg.value); // Update the total wei collected during the crowdfunding RLCSentToETH = safeAdd(RLCSentToETH, rlcToSend); emitRLC(rlcToSend); // compute the variable part ReceivedETH(beneficiary,ETHReceived); // send the corresponding contribution event } /* * receives a donation in BTC */ function receiveBTC(address beneficiary, string btc_address, uint value, string txid) stopInEmergency respectTimeFrame onlyBy(BTCproxy) returns (bool res){ if (value < minInvestBTC) throw; // this verif is also made on the btcproxy uint rlcToSend = bonus(safeMul(value,RLCPerSATOSHI)); //compute the number of RLC to send if (safeAdd(rlcToSend, safeAdd(RLCSentToETH, RLCSentToBTC)) > maxCap) { // check if we are not reaching the maxCap by accepting this donation RefundBTC(btc_address , value); return false; } Backer backer = backers[beneficiary]; if (!rlc.transfer(beneficiary, rlcToSend)) throw; // Do the transfer right now backer.rlcSent = safeAdd(backer.rlcSent , rlcToSend); backer.btc_address = btc_address; backer.satoshiReceived = safeAdd(backer.satoshiReceived, value); BTCReceived = safeAdd(BTCReceived, value); // Update the total satoshi collected during the crowdfunding for this backer RLCSentToBTC = safeAdd(RLCSentToBTC, rlcToSend); // Update the total satoshi collected during the crowdfunding emitRLC(rlcToSend); ReceivedBTC(beneficiary, btc_address, BTCReceived, txid); return true; } /* *Compute the variable part */ function emitRLC(uint amount) internal { rlc_bounty = safeAdd(rlc_bounty, amount/10); rlc_team = safeAdd(rlc_team, amount/20); rlc_reserve = safeAdd(rlc_reserve, amount/10); Logs(msg.sender ,amount, "emitRLC"); } /* *Compute the RLC bonus according to the investment period */ function bonus(uint amount) internal constant returns (uint) { if (now < safeAdd(startBlock, 10 days)) return (safeAdd(amount, amount/5)); // bonus 20% if (now < safeAdd(startBlock, 20 days)) return (safeAdd(amount, amount/10)); // bonus 10% return amount; } /* * When mincap is not reach backer can call the approveAndCall function of the RLC token contract * with this crowdsale contract on parameter with all the RLC they get in order to be refund */ function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) minCapNotReached public { if (msg.sender != address(rlc)) throw; if (_extraData.length != 0) throw; // no extradata needed if (_value != backers[_from].rlcSent) throw; // compare value from backer balance if (!rlc.transferFrom(_from, address(this), _value)) throw ; // get the token back to the crowdsale contract if (!rlc.burn(_value)) throw ; // token sent for refund are burnt uint ETHToSend = backers[_from].weiReceived; backers[_from].weiReceived=0; uint BTCToSend = backers[_from].satoshiReceived; backers[_from].satoshiReceived = 0; if (ETHToSend > 0) { asyncSend(_from,ETHToSend); // pull payment to get refund in ETH } if (BTCToSend > 0) RefundBTC(backers[_from].btc_address ,BTCToSend); // event message to manually refund BTC } /* * Update the rate RLC per ETH, computed externally by using the ETHBTC index on kraken every 10min */ function setRLCPerETH(uint rate) onlyBy(BTCproxy) { RLCPerETH=rate; } /* * Finalize the crowdsale, should be called after the refund period */ function finalize() onlyBy(owner) { // check if (RLCSentToETH + RLCSentToBTC < maxCap - 5000000000000 && now < endBlock) throw; // cannot finalise before 30 day until maxcap is reached minus 1BTC if (RLCSentToETH + RLCSentToBTC < minCap && now < endBlock + 15 days) throw ; // if mincap is not reached donors have 15days to get refund before we can finalise if (!multisigETH.send(this.balance)) throw; // moves the remaining ETH to the multisig address if (rlc_reserve > 6000000000000000){ // moves RLC to the team, reserve and bounty address if(!rlc.transfer(reserve,6000000000000000)) throw; // max cap 6000000RLC rlc_reserve = 6000000000000000; } else { if(!rlc.transfer(reserve,rlc_reserve)) throw; } if (rlc_bounty > 6000000000000000){ if(!rlc.transfer(bounty,6000000000000000)) throw; // max cap 6000000RLC rlc_bounty = 6000000000000000; } else { if(!rlc.transfer(bounty,rlc_bounty)) throw; } if (!rlc.transfer(team,rlc_team)) throw; uint RLCEmitted = rlc_reserve + rlc_bounty + rlc_team + RLCSentToBTC + RLCSentToETH; if (RLCEmitted < rlc.totalSupply()) // burn the rest of RLC rlc.burn(rlc.totalSupply() - RLCEmitted); rlc.unlock(); crowdsaleClosed = true; } /* * Failsafe drain */ function drain() onlyBy(owner) { if (!owner.send(this.balance)) throw; } }
Update the rate RLC per ETH, computed externally by using the ETHBTC index on kraken every 10min/
function setRLCPerETH(uint rate) onlyBy(BTCproxy) { RLCPerETH=rate; }
13,075,030
pragma experimental ABIEncoderV2; pragma solidity ^0.5.12; import "./LicenseOwnership.sol"; contract MarketplaceBase is LicenseOwnership { struct Sale { //unnecessary address productId; uint256 price; } struct Review { // address issuer; address productId; uint256 rating; bytes description; } Review[] reviews; // prices of an app mapping(address => Sale) productIdToSale; mapping(address => uint256) productTokenCount; event ProductRated( address productId, uint256 rating, bytes description, uint256 timestamp ); // interval specifies the duration of the subscription event SaleCreated(address productId, uint256 price); function _setPrice(address _productId, uint256 _price) internal { productIdToSale[_productId].price = _price; // PriceChanged(); } function createSale(address _productId, uint256 _price) external { // productIdToSale[_productId].price = _price; _setPrice(_productId, _price); // productIdToSale[_productId].interval = _interval; emit SaleCreated(_productId, _price); } function _performPurchase( address _productId, uint256 _numCycles, address _assignee ) internal returns (uint256) { return _createLicense(_productId, _numCycles, _assignee); } function _createLicense( address _productId, uint256 _numCycles, address _assignee ) internal returns (uint256) { //uint256 expirationTime = isSubscriptionProduct(_productId) ? // now.add(intervalOf(_productId).mul(_numCycles)) : // 0; License memory _license = License({ productId: _productId, issuedTime: now, expirationTime: _numCycles }); uint256 newLicenseId = licenses.push(_license) - 1; productTokenCount[_productId]++; emit LicenseIssued( _assignee, msg.sender, newLicenseId, _license.productId, _license.issuedTime, _license.expirationTime ); _mint(_assignee, newLicenseId); return newLicenseId; } function _performRating( uint256 tokenId, uint256 rating, bytes calldata description ) internal { Review memory review = Review({ productId: licenses[tokenId].productId, rating: rating, description: description }); reviews.push(review); emit ProductRated( review.productId, review.rating, review.description, block.timestamp ); } function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); //Transfers ownership per ERC721 draft _transfer(address(0), _to, _tokenId); } function purchaseService( address _productId, address _assignee, uint256 _numCycles ) external payable returns (uint256) { // transfer the value of the application to the user. require(_productId != address(0)); require(_assignee != address(0)); require(msg.value == productIdToSale[_productId].price); uint256 licenseId = _performPurchase(_productId, _numCycles, _assignee); return licenseId; } function rateProduct( uint256 tokenId, uint256 rating, bytes calldata description ) external { require(msg.sender == ownerOf(tokenId)); _performRating(tokenId, rating, description); } function getReviewIndexOfProduct(address productId) external view returns (uint256[] memory) { uint256 tokenCount = productTokenCount[productId]; if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; for (uint256 i = 0; i <= reviews.length; i++) { if (productId == reviews[i].productId) { result[resultIndex] = 0; resultIndex++; } } return result; } } function getReviewById(uint256 reviewIndex) external view returns (uint256, bytes memory) { return (reviews[reviewIndex].rating, reviews[reviewIndex].description); } }
uint256 expirationTime = isSubscriptionProduct(_productId) ? now.add(intervalOf(_productId).mul(_numCycles)) : 0;
function _createLicense( address _productId, uint256 _numCycles, address _assignee ) internal returns (uint256) { License memory _license = License({ productId: _productId, issuedTime: now, expirationTime: _numCycles }); uint256 newLicenseId = licenses.push(_license) - 1; productTokenCount[_productId]++; emit LicenseIssued( _assignee, msg.sender, newLicenseId, _license.productId, _license.issuedTime, _license.expirationTime ); _mint(_assignee, newLicenseId); return newLicenseId; }
1,011,310
//SPDX-License-Identifier: MIT //Contract is not audited, use at your own risk //https://github.com/ExtensionNFT/contracts pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./interfaces/IRenderExtension.sol"; import "./interfaces/ISvgValidator.sol"; // solhint-disable quotes contract Extension is Initializable, ERC721EnumerableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using StringsUpgradeable for uint256; using SafeERC20Upgradeable for IERC20; using SafeMathUpgradeable for uint256; bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; bytes4 public constant RENDER_INTERFACE_ID = type(IRenderExtension).interfaceId; uint256 public constant MAX_MINTS = 10; uint256 public constant REGISTRATION_COST = 200_000_000_000_000_000; uint256 public constant MINT_COST = 100_000_000_000_000_000; uint256 public constant MAX_EXTENSIONS = 8; struct GenerationDetails { uint256 mintNumStart; uint256 mintNumEnd; uint256 totalMinted; uint256 nextOwnerMintId; uint256 nextPublicMintId; uint256 maxOwnerMints; } mapping(uint256 => GenerationDetails) public generations; uint256 public currentGeneration; uint256 public currentExtensionSet; mapping(uint256 => uint256) public tokenExtensionSet; mapping(uint256 => address[]) public extensionSetAddresses; mapping(uint256 => uint256) public tokenGeneration; mapping(address => bool) public bannedAddresses; address public validatorAddress; bool public canModerate; address public moderator; function initialize( uint256 amtForInitGen, uint256 ownerMintsForInitGen, address validator ) public initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Extension NFT", "ExNFT"); __ERC721Enumerable_init_unchained(); __Ownable_init_unchained(); __ReentrancyGuard_init_unchained(); currentGeneration = 1; canModerate = true; moderator = msg.sender; generations[1] = GenerationDetails({ mintNumStart: 1, mintNumEnd: amtForInitGen, totalMinted: 0, nextOwnerMintId: 1, nextPublicMintId: 1 + ownerMintsForInitGen, maxOwnerMints: ownerMintsForInitGen }); validatorAddress = validator; } event ModerationRelinquished(); event ValidatorAddressSet(address validator); event ModeratorSet(address moderator); event AddressModerationChanged(address addr, bool allowed); event ExtensionAdded(address added, uint256 addedAt, address removed); event ExtensionReplaced(address newAddress, address oldAddress, uint256 index); event ExtensionRemoved(address extension, uint256 index); event NextGenerationStart(uint256 currentGeneration); event ETHExit(address to, uint256 amount); event ERC20Exit(address token, address to, uint256 amount); function relinquishModeration() external onlyOwner { require(canModerate, "NO_MODERATION"); canModerate = false; emit ModerationRelinquished(); } function setValidatorAddress(address validator) external onlyOwner { validatorAddress = validator; emit ValidatorAddressSet(validator); } function setModerator(address mod) external onlyOwner { moderator = mod; emit ModeratorSet(mod); } function moderateAddress(address modAddress, bool allowed) external onlyOwner { require(canModerate, "NO_MODERATION"); bannedAddresses[modAddress] = allowed; emit AddressModerationChanged(modAddress, allowed); } function addExtension(address contractAddress) external payable nonReentrant { require(!canModerate || (canModerate && !bannedAddresses[contractAddress]), "CONTRACT_BANNED"); require(!canModerate || (canModerate && !bannedAddresses[msg.sender]), "SENDER_BANNED"); require(contractAddress != address(0), "INVALID_ADDRESS"); require(IRenderExtension(contractAddress).supportsInterface(RENDER_INTERFACE_ID), "NO_RENDER_SUPPORT"); require(msg.value == REGISTRATION_COST || (canModerate && owner() == msg.sender), "NO_REGISTRATION_FEE"); uint256 newExtensionSetId = currentExtensionSet.add(1); uint256 currentExtensionSetLength = extensionSetAddresses[currentExtensionSet].length; uint256 i = 0; address removed = address(0); if (currentExtensionSetLength == MAX_EXTENSIONS) { i = 1; removed = extensionSetAddresses[currentExtensionSet][0]; } for (; i < currentExtensionSetLength; i++) { extensionSetAddresses[newExtensionSetId].push(extensionSetAddresses[currentExtensionSet][i]); } extensionSetAddresses[newExtensionSetId].push(contractAddress); currentExtensionSet = newExtensionSetId; emit ExtensionAdded(contractAddress, i, removed); } function replaceExtension( uint256 extensionIndex, address existingAddress, address contractAddress ) external payable nonReentrant { require(!canModerate || (canModerate && !bannedAddresses[contractAddress]), "CONTRACT_BANNED"); require(!canModerate || (canModerate && !bannedAddresses[msg.sender]), "SENDER_BANNED"); require(contractAddress != address(0), "INVALID_ADDRESS"); require(extensionSetAddresses[currentExtensionSet][extensionIndex] == existingAddress, "MISMATCH_REPLACE"); require(IRenderExtension(contractAddress).supportsInterface(RENDER_INTERFACE_ID), "NO_RENDER_SUPPORT"); require(msg.value == REGISTRATION_COST || (canModerate && owner() == msg.sender), "NO_REGISTRATION_FEE"); uint256 newExtensionSetId = currentExtensionSet.add(1); address replaced; for (uint256 i = 0; i < extensionSetAddresses[currentExtensionSet].length; i++) { if (i == extensionIndex) { replaced = extensionSetAddresses[currentExtensionSet][i]; extensionSetAddresses[newExtensionSetId].push(contractAddress); } else { extensionSetAddresses[newExtensionSetId].push(extensionSetAddresses[currentExtensionSet][i]); } } currentExtensionSet = newExtensionSetId; emit ExtensionReplaced(contractAddress, replaced, extensionIndex); } function removeExtension(uint256 extensionIndex, address existingAddress) external payable nonReentrant { require(!canModerate || (canModerate && !bannedAddresses[msg.sender]), "SENDER_BANNED"); require(extensionSetAddresses[currentExtensionSet][extensionIndex] == existingAddress, "MISMATCH_REPLACE"); require(msg.value == REGISTRATION_COST || (canModerate && owner() == msg.sender), "NO_REGISTRATION_FEE"); require(extensionSetAddresses[currentExtensionSet].length > 1, "MUST_HAVE_ONE"); uint256 newExtensionSetId = currentExtensionSet.add(1); for (uint256 i = 0; i < extensionSetAddresses[currentExtensionSet].length; i++) { if (i != extensionIndex) { extensionSetAddresses[newExtensionSetId].push(extensionSetAddresses[currentExtensionSet][i]); } } currentExtensionSet = newExtensionSetId; emit ExtensionRemoved(existingAddress, extensionIndex); } function mint(uint256 amtToMint) external payable { require(amtToMint > 0, "MUST_MINT_ONE"); require(amtToMint <= MAX_MINTS, "TOO_MANY"); require(msg.value == (amtToMint * MINT_COST), "INVALID_FUNDS"); require(generations[currentGeneration].nextPublicMintId.add(amtToMint).sub(1) <= generations[currentGeneration].mintNumEnd, "GENERATION_LOCKED"); for (uint256 i = 0; i < amtToMint; i++) { _mintTo(msg.sender, generations[currentGeneration].nextPublicMintId); generations[currentGeneration].nextPublicMintId = generations[currentGeneration].nextPublicMintId.add(1); } } function ownerMint(uint256 amtToMint, address to) external onlyOwner { require(amtToMint > 0, "MUST_MINT_ONE"); require(amtToMint <= MAX_MINTS, "TOO_MANY"); require( generations[currentGeneration].nextOwnerMintId.add(amtToMint).sub(1) < generations[currentGeneration].mintNumStart.add(generations[currentGeneration].maxOwnerMints), "OWNER_MINT_COMPLETE" ); for (uint256 i = 0; i < amtToMint; i++) { _mintTo(to, generations[currentGeneration].nextOwnerMintId); generations[currentGeneration].nextOwnerMintId = generations[currentGeneration].nextOwnerMintId.add(1); } } function nextGeneration(uint256 mintAmount, uint256 ownerMints) external onlyOwner { GenerationDetails memory prevGen = generations[currentGeneration]; require(prevGen.nextPublicMintId > prevGen.mintNumEnd, "PUBLIC_NOT_ENDED"); require(mintAmount > ownerMints, "GIVE_THE_PUBLIC_SOMETHING"); currentGeneration = currentGeneration.add(1); generations[currentGeneration] = GenerationDetails({ mintNumStart: prevGen.nextPublicMintId, mintNumEnd: prevGen.nextPublicMintId.add(mintAmount).sub(1), totalMinted: 0, nextOwnerMintId: prevGen.nextPublicMintId, nextPublicMintId: prevGen.nextPublicMintId.add(ownerMints), maxOwnerMints: ownerMints }); emit NextGenerationStart(currentGeneration); } function ethRecoup(address payable to, uint256 amount) external onlyOwner { require(to != address(0), "NO_BURN"); require(address(this).balance > 0, "NO_FUNDS"); require(amount > 0, "INVALID_AMOUNT"); require(to.send(amount), "SEND_FAIL"); emit ETHExit(to, amount); } function erc20Recoup( address token, address to, uint256 amount ) external onlyOwner { require(to != address(0), "NO_BURN"); require(token != address(0), "INVALID_TOKEN"); require(amount > 0, "INVALID_AMOUNT"); require(IERC20(token).balanceOf(address(this)) > 0, "NO_FUNDS"); IERC20(token).safeTransfer(to, amount); emit ERC20Exit(token, to, amount); } function getExtensionsSetAddresses(uint256 extensionSetId) external view returns (address[] memory addresses) { addresses = extensionSetAddresses[extensionSetId]; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "TOKEN_DOES_NOT_EXIST"); address[] memory extensions = extensionSetAddresses[tokenExtensionSet[tokenId]]; string[MAX_EXTENSIONS + 2] memory parts; string[MAX_EXTENSIONS + 6] memory attrs; parts[ 0 ] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 8px; }</style><rect width="100%" height="100%" fill="black" />'; // solhint-disable-line quotes attrs[0] = '[{"trait_type":"Generation","value":"'; attrs[1] = toString(tokenGeneration[tokenId]); attrs[2] = '"},{"trait_type":"Extension Set","value":"'; attrs[3] = toString(tokenExtensionSet[tokenId]); attrs[4] = '"}'; for (uint256 i = 0; i < extensions.length; i++) { if (extensions[i] != address(0)) { try IRenderExtension(extensions[i]).generate(tokenId, tokenGeneration[tokenId]) returns (IRenderExtension.GenerateResult memory result) { bool isValid = ISvgValidator(validatorAddress).isValid(result.svgPart); if (isValid == false) { parts[i + 1] = result.svgPart; attrs[i + 5] = result.attributes; } else { parts[i + 1] = ""; attrs[i + 5] = ""; } } catch { parts[i + 1] = ""; attrs[i + 5] = ""; } } else { parts[i + 1] = ""; attrs[i + 5] = ""; } } parts[MAX_EXTENSIONS - 1] = "</svg>"; attrs[attrs.length - 1] = "]"; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9])); string memory attrOutput = string(abi.encodePacked(attrs[0], attrs[1], attrs[2], attrs[3], attrs[4], attrs[5], attrs[6], attrs[7], attrs[8])); attrOutput = string(abi.encodePacked(attrOutput, attrs[9], attrs[10], attrs[11], attrs[12], attrs[13])); string memory json = base64Encode( bytes( string( abi.encodePacked( '{"name": "Extension NFT #', toString(tokenId), '", "description": "What has the community done to this NFT?", "attributes": ', attrOutput, ', "image": "data:image/svg+xml;base64,', base64Encode(bytes(output)), '"}' ) ) ) ); output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } function contractURI() public view returns (string memory) { string memory props = string( abi.encodePacked( '{"name": "Extension NFT", "description": "An experiment in community driven NFTs. When you can affect the look and rarity of your mint, where will your code fall? Creative Good or Developer Evil?",', '"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALEAAACrCAIAAACmBupvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAHYcAAB2HAY/l8WUAAAEmSURBVHhe7dahbkNBEARB//9PJ6SH25ECnrcKtnRoB9wLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB7p53O95Ft150/0km/VnT/RS75Vd/5EL/km3Xaq7+nNVHm67jnV9/Rmqjxd95zqe3ozVZ6ue071Pb2ZKpe1halyWVuYKpe1halyWVuYKpe1halyWVuYKpe1halyWVuYKtd0/6lyWVuYKpe1halyWVuYKtd0/6lyWVuYKpe1halyWVuYKtd0/6lyWVuYKpe1halyWVuYKpe1halyWVuYKpe1halyWVuYKgAA/F1/y6lyWVuYKpe1halyWVuYKgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/l9foFLnXlN+EHpoQAAAAASUVORK5CYII=",', '"seller_fee_basis_points": 100,', '"fee_recipient": "0x', getChecksum(address(this)), '"}' ) ); string memory json = base64Encode(bytes(props)); string memory output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } function _mintTo(address to, uint256 tokenId) internal { tokenGeneration[tokenId] = currentGeneration; tokenExtensionSet[tokenId] = currentExtensionSet; generations[currentGeneration].totalMinted = generations[currentGeneration].totalMinted; _safeMint(to, tokenId); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } function base64Encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; //solhint-disable assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } //solhint-enable return string(result); } /** * @dev Get a checksummed string hex representation of an account address. * @param account address The account to get the checksum for. * @return accountChecksum The checksummed account string in ASCII format. Note that leading * "0x" is not included. */ function getChecksum(address account) public pure returns (string memory accountChecksum) { // call internal function for converting an account to a checksummed string. return _toChecksumString(account); } /** * @dev Get a fixed-size array of whether or not each character in an account * will be capitalized in the checksum. * @param account address The account to get the checksum capitalization * information for. * @return characterCapitalized A fixed-size array of booleans that signify if each character or * "nibble" of the hex encoding of the address will be capitalized by the * checksum. */ function getChecksumCapitalizedCharacters(address account) public pure returns (bool[40] memory characterCapitalized) { // call internal function for computing characters capitalized in checksum. return _toChecksumCapsFlags(account); } /** * @dev Determine whether a string hex representation of an account address * matches the ERC-55 checksum of that address. * @param accountChecksum string The checksummed account string in ASCII * format. Note that a leading "0x" MUST NOT be included. * @return ok A boolean signifying whether or not the checksum is valid. */ function isChecksumValid(string calldata accountChecksum) public pure returns (bool ok) { // call internal function for validating checksum strings. return _isChecksumValid(accountChecksum); } function _toChecksumString(address account) internal pure returns (string memory asciiString) { // convert the account argument from address to bytes. bytes20 data = bytes20(account); // create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // declare variable types. uint8 b; uint8 leftNibble; uint8 rightNibble; bool leftCaps; bool rightCaps; uint8 asciiOffset; // get the capitalized characters in the actual checksum. bool[40] memory caps = _toChecksumCapsFlags(account); // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. b = uint8(uint160(data) / (2**(8 * (19 - i)))); leftNibble = b / 16; rightNibble = b - 16 * leftNibble; // locate and extract each capitalization status. leftCaps = caps[2 * i]; rightCaps = caps[2 * i + 1]; // get the offset from nibble value to ascii character for left nibble. asciiOffset = _getAsciiOffset(leftNibble, leftCaps); // add the converted character to the byte array. asciiBytes[2 * i] = bytes1(leftNibble + asciiOffset); // get the offset from nibble value to ascii character for right nibble. asciiOffset = _getAsciiOffset(rightNibble, rightCaps); // add the converted character to the byte array. asciiBytes[2 * i + 1] = bytes1(rightNibble + asciiOffset); } return string(asciiBytes); } function _toChecksumCapsFlags(address account) internal pure returns (bool[40] memory characterCapitalized) { // convert the address to bytes. bytes20 a = bytes20(account); // hash the address (used to calculate checksum). bytes32 b = keccak256(abi.encodePacked(_toAsciiString(a))); // declare variable types. uint8 leftNibbleAddress; uint8 rightNibbleAddress; uint8 leftNibbleHash; uint8 rightNibbleHash; // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i; i < a.length; i++) { // locate the byte and extract each nibble for the address and the hash. rightNibbleAddress = uint8(a[i]) % 16; leftNibbleAddress = (uint8(a[i]) - rightNibbleAddress) / 16; rightNibbleHash = uint8(b[i]) % 16; leftNibbleHash = (uint8(b[i]) - rightNibbleHash) / 16; characterCapitalized[2 * i] = (leftNibbleAddress > 9 && leftNibbleHash > 7); characterCapitalized[2 * i + 1] = (rightNibbleAddress > 9 && rightNibbleHash > 7); } } function _isChecksumValid(string memory provided) internal pure returns (bool ok) { // convert the provided string into account type. address account = _toAddress(provided); // return false in the event the account conversion returned null address. if (account == address(0)) { // ensure that provided address is not also the null address first. bytes memory b = bytes(provided); for (uint256 i; i < b.length; i++) { if (b[i] != hex"30") { return false; } } } // get the capitalized characters in the actual checksum. string memory actual = _toChecksumString(account); // compare provided string to actual checksum string to test for validity. return (keccak256(abi.encodePacked(actual)) == keccak256(abi.encodePacked(provided))); } function _getAsciiOffset(uint8 nibble, bool caps) internal pure returns (uint8 offset) { // to convert to ascii characters, add 48 to 0-9, 55 to A-F, & 87 to a-f. if (nibble < 10) { offset = 48; } else if (caps) { offset = 55; } else { offset = 87; } } function _toAddress(string memory account) internal pure returns (address accountAddress) { // convert the account argument from address to bytes. bytes memory accountBytes = bytes(account); // create a new fixed-size byte array for the ascii bytes of the address. bytes memory accountAddressBytes = new bytes(20); // declare variable types. uint8 b; uint8 nibble; uint8 asciiOffset; // only proceed if the provided string has a length of 40. if (accountBytes.length == 40) { for (uint256 i; i < 40; i++) { // get the byte in question. b = uint8(accountBytes[i]); // ensure that the byte is a valid ascii character (0-9, A-F, a-f) if (b < 48) return address(0); if (57 < b && b < 65) return address(0); if (70 < b && b < 97) return address(0); if (102 < b) return address(0); //bytes(hex""); // find the offset from ascii encoding to the nibble representation. if (b < 65) { // 0-9 asciiOffset = 48; } else if (70 < b) { // a-f asciiOffset = 87; } else { // A-F asciiOffset = 55; } // store left nibble on even iterations, then store byte on odd ones. if (i % 2 == 0) { nibble = b - asciiOffset; } else { accountAddressBytes[(i - 1) / 2] = (bytes1(16 * nibble + (b - asciiOffset))); } } // pack up the fixed-size byte array and cast it to accountAddress. bytes memory packed = abi.encodePacked(accountAddressBytes); assembly { accountAddress := mload(add(packed, 20)) } } } // based on https://ethereum.stackexchange.com/a/56499/48410 function _toAsciiString(bytes20 data) internal pure returns (string memory asciiString) { // create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // declare variable types. uint8 b; uint8 leftNibble; uint8 rightNibble; // iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. b = uint8(uint160(data) / (2**(8 * (19 - i)))); leftNibble = b / 16; rightNibble = b - 16 * leftNibble; // to convert to ascii characters, add 48 to 0-9 and 87 to a-f. asciiBytes[2 * i] = bytes1(leftNibble + (leftNibble < 10 ? 48 : 87)); asciiBytes[2 * i + 1] = bytes1(rightNibble + (rightNibble < 10 ? 48 : 87)); } return string(asciiBytes); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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 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 { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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 "../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; /** * @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; /** * @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"; import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable 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( IERC20Upgradeable 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( IERC20Upgradeable 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(IERC20Upgradeable 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; // 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 SafeMathUpgradeable { /** * @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; } } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IRenderExtension is IERC165 { struct GenerateResult { string svgPart; string attributes; } struct Attribute { string displayType; string traitType; string value; } function generate(uint256 tokenId, uint256 generationId) external view returns (GenerateResult memory generateResult); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ISvgValidator { function isValid(string memory check) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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 IERC721ReceiverUpgradeable { /** * @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 "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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 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; 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 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; 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) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // 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 IERC165Upgradeable { /** * @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 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); }
multiply by 4/3 rounded up Add some extra buffer at the endsolhint-disable
function base64Encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; uint256 encodedLen = 4 * ((len + 2) / 3); bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); }
1,572,943
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/AssetHelpers.sol"; import "./Moartroller.sol"; import "./SimplePriceOracle.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers { /** * @notice get the maximum asset value that can be still optimized. * @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value' * which is helpful to recalculate how much of this protection can be optimized again */ function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){ uint returnValue; uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments); uint totalProtectionLockedValue; (totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments); if(hypotheticalOptimizableValue <= totalProtectionLockedValue){ returnValue = 0; } else{ returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue); } return returnValue; } /** * @notice get the maximum value of an asset that can be optimized by protection for the given user * @dev optimizable = asset value * MPC * @return the hypothetical optimizable value * TODO: replace hardcoded 1e18 values */ function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) { uint assetValue = div_( mul_( div_( mul_( arguments.asset.balanceOf(arguments.account), arguments.asset.exchangeRateStored() ), 1e18 ), arguments.oracle.getUnderlyingPrice(arguments.asset) ), getAssetDecimalsMantissa(arguments.asset.getUnderlying()) ); uint256 hypotheticalOptimizableValue = div_( mul_( assetValue, arguments.asset.maxProtectionComposition() ), arguments.asset.maxProtectionCompositionMantissa() ); return hypotheticalOptimizableValue; } /** * @dev gets all locked protections values with mark to market value. Used by Moartroller. */ function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) { uint _lockedValue = 0; uint _markToMarket = 0; uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying()); for (uint j = 0; j < _protectionCount; j++) { uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j); bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId); if(protectionIsAlive){ _lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId)); uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset); uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId); if( assetSpotPrice > protectionStrikePrice) { _markToMarket = _markToMarket + div_( mul_( div_( mul_( assetSpotPrice - protectionStrikePrice, arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId) ), getAssetDecimalsMantissa(arguments.asset.underlying()) ), arguments.collateralFactorMantissa ), 1e18 ); } } } return (_lockedValue , _markToMarket); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "../MToken.sol"; import "../MProtection.sol"; import "../Interfaces/PriceOracle.sol"; interface LiquidityMathModelInterface { struct LiquidityMathArgumentsSet { MToken asset; address account; uint collateralFactorMantissa; MProtection cprotection; PriceOracle oracle; } function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint); function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint); function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Utils/ErrorReporter.sol"; import "./Utils/Exponential.sol"; import "./Interfaces/EIP20Interface.sol"; import "./MTokenStorage.sol"; import "./Interfaces/MTokenInterface.sol"; import "./Interfaces/MProxyInterface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; /** * @title MOAR's MToken Contract * @notice Abstract base for MTokens * @author MOAR */ abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage { /** * @notice Indicator that this is a MToken contract (for inspection) */ bool public constant isMToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when moartroller is changed */ event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /** * @notice Max protection composition value updated event */ event MpcUpdated(uint newValue); /** * @notice Initialize the money market * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function init(Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "not_admin"); require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "too_low"); // Set the moartroller uint err = _setMoartroller(moartroller_); require(err == uint(Error.NO_ERROR), "setting moartroller failed"); // Initialize block number and borrow index (block number mocks depend on moartroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; maxProtectionComposition = 5000; maxProtectionCompositionMantissa = 1e4; reserveFactorMaxMantissa = 1e18; borrowRateMaxMantissa = 0.0005e16; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srmTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srmTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // moartroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external virtual override returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external virtual override view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external virtual override view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external virtual override returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance_calculation_failed"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by moartroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) { uint mTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this mToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this mToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public virtual view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public virtual nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public virtual view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this mToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external virtual override view returns (uint) { return getCashPrior(); } function getRealBorrowIndex() public view returns (uint) { uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); Exp memory simpleInterestFactor; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor"); (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex"); return borrowIndexNew; } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public virtual returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; AccrueInterestTempStorage memory temp; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = temp.borrowIndexNew; totalBorrows = temp.totalBorrowsNew; totalReserves = temp.totalReservesNew; if(temp.splitedReserves_2 > 0){ address mProxy = moartroller.mProxy(); EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2); MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2); } /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives mTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the mToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of mTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* * We calculate the new total supply of mTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems mTokens 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 receive from redeeming mTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems mTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } /* Fail if user tries to redeem more than he has locked with c-op*/ // TODO: update error codes uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18); if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @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 borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) { require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing"); uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(borrower, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow 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 borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ //unused function // moartroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ /* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */ if (repayAmount == uint(-1)) { require(tx.origin == borrower, "specify a precise amount"); vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = mTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify mTokenCollateral market's block number equals current block number */ if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower); require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(mTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another mToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken. * Its absolutely critical to use msg.sender as the seizer mToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed mToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external virtual override returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new moartroller for the market * @dev Admin function to set a new moartroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK); } Moartroller oldMoartroller = moartroller; // Ensure invoke moartroller.isMoartroller() returns true require(newMoartroller.isMoartroller(), "not_moartroller"); // Set market's moartroller to newMoartroller moartroller = newMoartroller; // Emit NewMoartroller(oldMoartroller, newMoartroller) emit NewMoartroller(oldMoartroller, newMoartroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } reserveSplitFactorMantissa = newReserveSplitFactorMantissa; return uint(Error.NO_ERROR); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModelInterface oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "not_interest_model"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /** * @notice Sets new value for max protection composition parameter * @param newMPC New value of MPC * @return uint 0=success, otherwise a failure */ function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){ if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } maxProtectionComposition = newMPC; emit MpcUpdated(newMPC); return uint(Error.NO_ERROR); } /** * @notice Returns address of underlying token * @return address of underlying token */ function getUnderlying() external override view returns(address){ return underlying; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal virtual view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal virtual returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal virtual; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; contract MoartrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, MOARTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_PROTECTION_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, MOARTROLLER_REJECTION, MOARTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_MOARTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_MOARTROLLER_REJECTION, LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_MOARTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_MOARTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_MOARTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_MOARTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_MOARTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract LiquidityMathModelErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, PRICE_ERROR, SNAPSHOT_ERROR } enum FailureInfo { ORACLE_PRICE_CHECK_FAILED } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Exponential module for storing fixed-precision decimals * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { 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 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 Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @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)}); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../Interfaces/EIP20Interface.sol"; contract AssetHelpers { /** * @dev return asset decimals mantissa. Returns 1e18 if ETH */ function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){ uint assetDecimals = 1e18; if (assetAddress != address(0)) { EIP20Interface token = EIP20Interface(assetAddress); assetDecimals = 10 ** uint256(token.decimals()); } return assetDecimals; } } // SPDX-License-Identifier: BSD-3-Clause // Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon. pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/MoartrollerInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Interfaces/MProxyInterface.sol"; import "./MoartrollerStorage.sol"; import "./Governance/UnionGovernanceToken.sol"; import "./MProtection.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./LiquidityMathModelV1.sol"; import "./Utils/SafeEIP20.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title MOAR's Moartroller Contract * @author MOAR */ contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable { using SafeEIP20 for EIP20Interface; /// @notice Indicator that this is a Moartroller contract (for inspection) bool public constant isMoartroller = true; /// @notice Emitted when an admin supports a market event MarketListed(MToken mToken); /// @notice Emitted when an account enters a market event MarketEntered(MToken mToken, address account); /// @notice Emitted when an account exits a market event MarketExited(MToken mToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when protection is changed event NewCProtection(MProtection oldCProtection, MProtection newCProtection); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPausedMToken(MToken mToken, string action, bool pauseState); /// @notice Emitted when a new MOAR speed is calculated for a market event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed); /// @notice Emitted when a new MOAR speed is set for a contributor event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed); /// @notice Emitted when MOAR is distributed to a supplier event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex); /// @notice Emitted when MOAR is distributed to a borrower event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex); /// @notice Emitted when borrow cap for a mToken is changed event NewBorrowCap(MToken indexed mToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when MOAR is granted by admin event MoarGranted(address recipient, uint amount); event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel); event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel); /// @notice The initial MOAR index for a market uint224 public constant moarInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // Custom initializer function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer { admin = msg.sender; liquidityMathModel = mathModel; liquidationModel = lqdModel; rewardClaimEnabled = false; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (MToken[] memory) { MToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, MToken mToken) external view returns (bool) { return markets[address(mToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) { uint len = mTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { MToken mToken = MToken(mTokens[i]); results[i] = uint(addToMarketInternal(mToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param mToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(mToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(mToken); emit MarketEntered(mToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address mTokenAddress) external override returns (uint) { MToken mToken = MToken(mTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the mToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(mToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set mToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete mToken from the account’s list of assets */ // load into memory for faster iteration MToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == mToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 MToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(mToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param mToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[mToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, minter); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) { uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[mToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param mToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { // Shh - currently unused mToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { // only mTokens may call borrowAllowed if borrower not in market require(msg.sender == mToken, "sender must be mToken"); // attempt to add borrower to the market Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[mToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[mToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = MToken(mToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused liquidator; if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) { return uint(Error.MOARTROLLER_MISMATCH); } // Keep the flywheel moving updateMoarSupplyIndex(mTokenCollateral); distributeSupplierMoar(mTokenCollateral, borrower); distributeSupplierMoar(mTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(mToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, src); distributeSupplierMoar(mToken, dst); return uint(Error.NO_ERROR); } /*** Liquidity/Liquidation Calculations ***/ /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address mTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, MToken mTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in MToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { MToken asset = assets[i]; address _account = account; // Read the balances and exchange rate from the mToken (oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals())); // Pre-compute a conversion factor from tokens -> dai (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * mTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral); // Protection value calculation sumCollateral += protectionValueLocked // Mark to market value calculation sumCollateral += markToMarketValue uint protectionValueLocked; uint markToMarketValue; (protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle)); if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) { vars.sumCollateral = 0; } else { vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor)); } vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked); vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with mTokenModify if (asset == mTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); _account = account; } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Returns the value of possible optimization left for asset * @param asset The MToken address * @param account The owner of asset * @return The value of possible optimization */ function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getMaxOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } /** * @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset * @param asset The MToken address * @param account The owner of asset * @return The amount of hypothetical optimization */ function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getHypotheticalOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) { return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens( LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet( oracle, this, mTokenBorrowed, mTokenCollateral, actualRepayAmount, account, liquidationIncentiveMantissa ) ); } /** * @notice Returns the amount of a specific asset that is locked under all c-ops * @param asset The MToken address * @param account The owner of asset * @return The amount of asset locked under c-ops */ function getUserLockedAmount(MToken asset, address account) public override view returns(uint) { uint protectionLockedAmount; address currency = asset.underlying(); uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency); for (uint i = 0; i < numOfProtections; i++) { uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i); if(cprotection.isProtectionAlive(cProtectionId)){ protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId); } } return protectionLockedAmount; } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the moartroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the moartroller PriceOracle oldOracle = oracle; // Set moartroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets a new CProtection that is allowed to use as a collateral optimisation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setProtection(address newCProtection) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } MProtection oldCProtection = cprotection; cprotection = MProtection(newCProtection); // Emit NewPriceOracle(oldOracle, newOracle) emit NewCProtection(oldCProtection, cprotection); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param mToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } // TODO: this check is temporary switched off. we can make exception for UNN later // Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // // // Check collateral factor <= 0.9 // Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); // if (lessThanExp(highLimit, newCollateralFactorExp)) { // return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); // } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } function _setRewardClaimEnabled(bool status) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); rewardClaimEnabled = status; return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(MToken mToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(mToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } mToken.isMToken(); // Sanity check to make sure its really a MToken // Note that isMoared is not in active use anymore markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0}); tokenAddressToMToken[address(mToken.underlying())] = mToken; _addMarketInternal(address(mToken)); emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address mToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != MToken(mToken), "market already added"); } allMarkets.push(MToken(mToken)); } /** * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = mTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(mTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(mTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Mint", state); return state; } function _setBorrowPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == moartrollerImplementation; } /*** MOAR Distribution ***/ /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal { uint currentMoarSpeed = moarSpeeds[address(mToken)]; if (currentMoarSpeed != 0) { // note that MOAR speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarSupplyIndex(address(mToken)); updateMoarBorrowIndex(address(mToken), borrowIndex); } else if (moarSpeed != 0) { // Add the MOAR market Market storage market = markets[address(mToken)]; require(market.isListed == true, "MOAR market is not listed"); if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) { moarSupplyState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) { moarBorrowState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentMoarSpeed != moarSpeed) { moarSpeeds[address(mToken)] = moarSpeed; emit MoarSpeedUpdated(mToken, moarSpeed); } } /** * @notice Accrue MOAR to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateMoarSupplyIndex(address mToken) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; uint supplySpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = MToken(mToken).totalSupply(); uint moarAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); moarSupplyState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue MOAR to the market by updating the borrow index * @param mToken The market whose borrow index to update */ function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; uint borrowSpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex); uint moarAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); moarBorrowState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate MOAR accrued by a supplier and possibly transfer it to them * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOAR to */ function distributeSupplierMoar(address mToken, address supplier) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]}); moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = moarInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = MToken(mToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta); moarAccrued[supplier] = supplierAccrued; emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate MOAR accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOAR to */ function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]}); moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta); moarAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate additional accrued MOAR for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint moarSpeed = moarContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && moarSpeed > 0) { uint newAccrued = mul_(deltaBlocks, moarSpeed); uint contributorAccrued = add_(moarAccrued[contributor], newAccrued); moarAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Claim all the MOAR accrued by holder in all markets * @param holder The address to claim MOAR for */ function claimMoarReward(address holder) public { return claimMoar(holder, allMarkets); } /** * @notice Claim all the MOAR accrued by holder in the specified markets * @param holder The address to claim MOAR for * @param mTokens The list of markets to claim MOAR in */ function claimMoar(address holder, MToken[] memory mTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimMoar(holders, mTokens, true, true); } /** * @notice Claim all MOAR accrued by the holders * @param holders The addresses to claim MOAR for * @param mTokens The list of markets to claim MOAR in * @param borrowers Whether or not to claim MOAR earned by borrowing * @param suppliers Whether or not to claim MOAR earned by supplying */ function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public { require(rewardClaimEnabled, "reward claim is disabled"); for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; require(markets[address(mToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarBorrowIndex(address(mToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerMoar(address(mToken), holders[j], borrowIndex); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } if (suppliers == true) { updateMoarSupplyIndex(address(mToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierMoar(address(mToken), holders[j]); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } } } /** * @notice Transfer MOAR to the user * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param user The address of the user to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer * @return The amount of MOAR which was NOT transferred to the user */ function grantMoarInternal(address user, uint amount) internal returns (uint) { EIP20Interface moar = EIP20Interface(getMoarAddress()); uint moarRemaining = moar.balanceOf(address(this)); if (amount > 0 && amount <= moarRemaining) { moar.approve(mProxy, amount); MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount); return 0; } return amount; } /*** MOAR Distribution Admin ***/ /** * @notice Transfer MOAR to the recipient * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param recipient The address of the recipient to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer */ function _grantMoar(address recipient, uint amount) public { require(adminOrInitializing(), "only admin can grant MOAR"); uint amountLeft = grantMoarInternal(recipient, amount); require(amountLeft == 0, "insufficient MOAR for grant"); emit MoarGranted(recipient, amount); } /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function _setMoarSpeed(MToken mToken, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); setMoarSpeedInternal(mToken, moarSpeed); } /** * @notice Set MOAR speed for a single contributor * @param contributor The contributor whose MOAR speed to update * @param moarSpeed New MOAR speed for contributor */ function _setContributorMoarSpeed(address contributor, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); // note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (moarSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } else { lastContributorBlock[contributor] = getBlockNumber(); } moarContributorSpeeds[contributor] = moarSpeed; emit ContributorMoarSpeedUpdated(contributor, moarSpeed); } /** * @notice Set liquidity math model implementation * @param mathModel the math model implementation */ function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel; liquidityMathModel = mathModel; emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel)); } /** * @notice Set liquidation model implementation * @param newLiquidationModel the liquidation model implementation */ function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public { require(msg.sender == admin, "only admin can set liquidation model implementation"); LiquidationModelInterface oldLiquidationModel = liquidationModel; liquidationModel = newLiquidationModel; emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel)); } function _setMoarToken(address moarTokenAddress) public { require(msg.sender == admin, "only admin can set MOAR token address"); moarToken = moarTokenAddress; } function _setMProxy(address mProxyAddress) public { require(msg.sender == admin, "only admin can set MProxy address"); mProxy = mProxyAddress; } /** * @notice Add new privileged address * @param privilegedAddress address to add */ function _addPrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); privilegedAddresses[privilegedAddress] = 1; } /** * @notice Remove privileged address * @param privilegedAddress address to remove */ function _removePrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); delete privilegedAddresses[privilegedAddress]; } /** * @notice Check if address if privileged * @param privilegedAddress address to check */ function isPrivilegedAddress(address privilegedAddress) public view returns (bool) { return privilegedAddresses[privilegedAddress] == 1; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (MToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the MOAR token * @return The address of MOAR */ function getMoarAddress() public view returns (address) { return moarToken; } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/PriceOracle.sol"; import "./CErc20.sol"; /** * Temporary simple price feed */ contract SimplePriceOracle is PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; mapping(address => uint) prices; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(MToken mToken) public override view returns (uint) { if (compareStrings(mToken.symbol(), "mDAI")) { return 1e18; } else { return prices[address(MErc20(address(mToken)).underlying())]; } } function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public { address asset = address(MErc20(address(mToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((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.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./Interfaces/CopMappingInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Moartroller.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/AssetHelpers.sol"; import "./MToken.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MProtection Contract * @notice Collateral optimization ERC-721 wrapper * @author MOAR */ contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable { using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; /** * @notice Event emitted when new MProtection token is minted */ event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime); /** * @notice Event emitted when MProtection token is redeemed */ event Redeem(address redeemer, uint tokenId, uint underlyingTokenId); /** * @notice Event emitted when MProtection token changes its locked value */ event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue); /** * @notice Event emitted when maturity window parameter is changed */ event MaturityWindowUpdated(uint newMaturityWindow); Counters.Counter private _tokenIds; address private _copMappingAddress; address private _moartrollerAddress; mapping (uint256 => uint256) private _underlyingProtectionTokensMapping; mapping (uint256 => uint256) private _underlyingProtectionLockedValue; mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping; uint256 public _maturityWindow; struct ProtectionMappedData{ address pool; address underlyingAsset; uint256 amount; uint256 strike; uint256 premium; uint256 lockedValue; uint256 totalValue; uint issueTime; uint expirationTime; bool isProtectionAlive; } /** * @notice Constructor for MProtection contract * @param copMappingAddress The address of data mapper for C-OP * @param moartrollerAddress The address of the Moartroller */ function initialize(address copMappingAddress, address moartrollerAddress) public initializer { __Ownable_init(); __ERC721_init("c-uUNN OC-Protection", "c-uUNN"); _copMappingAddress = copMappingAddress; _moartrollerAddress = moartrollerAddress; _setMaturityWindow(10800); // 3 hours default } /** * @notice Returns C-OP mapping contract */ function copMapping() private view returns (CopMappingInterface){ return CopMappingInterface(_copMappingAddress); } /** * @notice Mint new MProtection token * @param underlyingTokenId Id of C-OP token that will be deposited * @return ID of minted MProtection token */ function mint(uint256 underlyingTokenId) public returns (uint256) { return mintFor(underlyingTokenId, msg.sender); } /** * @notice Mint new MProtection token for specified address * @param underlyingTokenId Id of C-OP token that will be deposited * @param receiver Address that will receive minted Mprotection token * @return ID of minted MProtection token */ function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256) { CopMappingInterface copMappingInstance = copMapping(); ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); addUProtectionIndexes(receiver, newItemId, underlyingTokenId); emit Mint( receiver, newItemId, underlyingTokenId, copMappingInstance.getUnderlyingAsset(underlyingTokenId), copMappingInstance.getUnderlyingAmount(underlyingTokenId), copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId), copMappingInstance.getUnderlyingDeadline(underlyingTokenId) ); return newItemId; } /** * @notice Redeem C-OP token * @param tokenId Id of MProtection token that will be withdrawn * @return ID of redeemed C-OP token */ function redeem(uint256 tokenId) external returns (uint256) { require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved"); uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId); removeProtectionIndexes(tokenId); _burn(tokenId); emit Redeem(msg.sender, tokenId, underlyingTokenId); return underlyingTokenId; } /** * @notice Returns set of C-OP data * @param tokenId Id of MProtection token * @return ProtectionMappedData struct filled with C-OP data */ function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){ ProtectionMappedData memory data; (address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId); data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId)); return data; } /** * @notice Returns underlying token ID * @param tokenId Id of MProtection token */ function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){ return _underlyingProtectionTokensMapping[tokenId]; } /** * @notice Returns size of C-OPs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].length(); } /** * @notice Returns list of C-OP IDs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].at(index); } /** * @notice Checks if address is owner of MProtection * @param owner Address of potential owner to check * @param tokenId ID of MProtection to check */ function isUserProtection(address owner, uint256 tokenId) public view returns(bool) { if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){ return true; } return owner == ownerOf(tokenId); } /** * @notice Checks if MProtection is stil alive * @param tokenId ID of MProtection to check */ function isProtectionAlive(uint256 tokenId) public view returns(bool) { uint256 deadline = getUnderlyingDeadline(tokenId); return (deadline - _maturityWindow) > now; } /** * @notice Creates appropriate indexes for C-OP * @param owner C-OP owner address * @param tokenId ID of MProtection * @param underlyingTokenId ID of C-OP */ function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{ address currency = copMapping().getUnderlyingAsset(underlyingTokenId); _underlyingProtectionTokensMapping[tokenId] = underlyingTokenId; _protectionCurrencyMapping[owner][currency].add(tokenId); } /** * @notice Remove indexes for C-OP * @param tokenId ID of MProtection */ function removeProtectionIndexes(uint256 tokenId) private{ address owner = ownerOf(tokenId); address currency = getUnderlyingAsset(tokenId); _underlyingProtectionTokensMapping[tokenId] = 0; _protectionCurrencyMapping[owner][currency].remove(tokenId); } /** * @notice Returns C-OP total value * @param tokenId ID of MProtection */ function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); return div_( mul_( getUnderlyingStrikePrice(tokenId), getUnderlyingAmount(tokenId) ), assetDecimalsMantissa ); } /** * @notice Returns C-OP locked value * @param tokenId ID of MProtection */ function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){ return _underlyingProtectionLockedValue[tokenId]; } /** * @notice get the amount of underlying asset that is locked * @param tokenId CProtection tokenId * @return amount locked */ function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); // calculates total protection value uint256 protectionValue = div_( mul_( getUnderlyingAmount(tokenId), getUnderlyingStrikePrice(tokenId) ), assetDecimalsMantissa ); // return value is lockedValue / totalValue * amount return div_( mul_( getUnderlyingAmount(tokenId), div_( mul_( _underlyingProtectionLockedValue[tokenId], 1e18 ), protectionValue ) ), 1e18 ); } /** * @notice Locks the given protection value as collateral optimization * @param tokenId The MProtection token id * @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization * @return locked protection value * TODO: convert semantic errors to standarized error codes */ function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) { //check if the protection belongs to the caller require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION"); address currency = getUnderlyingAsset(tokenId); Moartroller moartroller = Moartroller(_moartrollerAddress); MToken mToken = moartroller.tokenAddressToMToken(currency); require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE"); uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId); uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId)); // add protection locked value if any uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId); if ( protectionLockedValue > 0) { maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue); } uint valueToLock; if (value != 0) { // check if lock value is at most max optimizable value require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE"); // check if lock value is at most protection total value require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE"); valueToLock = value; } else { // if we want to lock maximum protection value let's lock the value that is at most max optimizable value if (protectionTotalValue > maxOptimizableValue) { valueToLock = maxOptimizableValue; } else { valueToLock = protectionTotalValue; } } _underlyingProtectionLockedValue[tokenId] = valueToLock; emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock); return valueToLock; } function _setCopMapping(address newMapping) public onlyOwner { _copMappingAddress = newMapping; } function _setMoartroller(address newMoartroller) public onlyOwner { _moartrollerAddress = newMoartroller; } function _setMaturityWindow(uint256 maturityWindow) public onlyOwner { emit MaturityWindowUpdated(maturityWindow); _maturityWindow = maturityWindow; } // MAPPINGS function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getProtectionData(underlyingTokenId); } function getUnderlyingAsset(uint256 tokenId) public view returns (address){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAsset(underlyingTokenId); } function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAmount(underlyingTokenId); } function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingStrikePrice(underlyingTokenId); } function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingDeadline(underlyingTokenId); } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface PriceOracle { /** * @notice Get the underlying price of a mToken asset * @param mToken The mToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(MToken mToken) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @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); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; abstract contract MTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @dev EIP-20 token name for this token */ string public name; /** * @dev EIP-20 token symbol for this token */ string public symbol; /** * @dev EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Underlying asset for this MToken */ address public underlying; /** * @dev Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal borrowRateMaxMantissa; /** * @dev Maximum fraction of interest that can be set aside for reserves */ uint internal reserveFactorMaxMantissa; /** * @dev Administrator for this contract */ address payable public admin; /** * @dev Pending administrator for this contract */ address payable public pendingAdmin; /** * @dev Contract which oversees inter-mToken operations */ Moartroller public moartroller; /** * @dev Model which tells what the current interest rate should be */ AbstractInterestRateModel public interestRateModel; /** * @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @dev Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @dev Fraction of reserves currently set aside for other usage */ uint public reserveSplitFactorMantissa; /** * @dev Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @dev Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @dev Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @dev Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @dev Total number of tokens in circulation */ uint public totalSupply; /** * @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000 */ uint public maxProtectionComposition; /** * @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5 */ uint public maxProtectionCompositionMantissa; /** * @dev Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @dev Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; struct ProtectionUsage { uint256 protectionValueUsed; } /** * @dev Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; mapping (uint256 => ProtectionUsage) protectionsUsed; } struct AccrueInterestTempStorage{ uint interestAccumulated; uint reservesAdded; uint splitedReserves_1; uint splitedReserves_2; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; } /** * @dev Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) public accountBorrows; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./EIP20Interface.sol"; interface MTokenInterface { /*** User contract ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom(address src, address dst, uint256 amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function getCash() external view returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); function getUnderlying() external view returns(address); function sweepToken(EIP20Interface token) external; /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface MProxyInterface { function proxyClaimReward(address asset, address recipient, uint amount) external; function proxySplitReserves(address asset, uint amount) external; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/InterestRateModelInterface.sol"; abstract contract AbstractInterestRateModel is InterestRateModelInterface { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Careful Math * @author MOAR * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ 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); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; import "../Utils/ExponentialNoError.sol"; interface MoartrollerInterface { /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `mTokenBalance` is the number of mTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint mTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; ExponentialNoError.Exp collateralFactor; ExponentialNoError.Exp exchangeRate; ExponentialNoError.Exp oraclePrice; ExponentialNoError.Exp tokensToDenom; } /*** Assets You Are In ***/ function enterMarkets(address[] calldata mTokens) external returns (uint[] memory); function exitMarket(address mToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint); function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint); function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeUserTokens( address mTokenBorrowed, address mTokenCollateral, uint repayAmount, address account) external view returns (uint, uint); function getUserLockedAmount(MToken asset, address account) external view returns(uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface Versionable { function getContractVersion() external pure returns (string memory); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "./MProtection.sol"; abstract contract UnitrollerAdminStorage { /** * @dev Administrator for this contract */ address public admin; /** * @dev Pending administrator for this contract */ address public pendingAdmin; /** * @dev Active brains of Unitroller */ address public moartrollerImplementation; /** * @dev Pending brains of Unitroller */ address public pendingMoartrollerImplementation; } contract MoartrollerV1Storage is UnitrollerAdminStorage { /** * @dev Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @dev Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @dev Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @dev Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => MToken[]) public accountAssets; } contract MoartrollerV2Storage is MoartrollerV1Storage { struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; // Whether or not this market receives MOAR bool isMoared; } /** * @dev Official mapping of mTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @dev The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract MoartrollerV3Storage is MoartrollerV2Storage { struct MoarMarketState { // The market's last updated moarBorrowIndex or moarSupplyIndex uint224 index; // The block number the index was last updated at uint32 block; } /// @dev A list of all markets MToken[] public allMarkets; /// @dev The rate at which the flywheel distributes MOAR, per block uint public moarRate; /// @dev The portion of moarRate that each market currently receives mapping(address => uint) public moarSpeeds; /// @dev The MOAR market supply state for each market mapping(address => MoarMarketState) public moarSupplyState; /// @dev The MOAR market borrow state for each market mapping(address => MoarMarketState) public moarBorrowState; /// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarSupplierIndex; /// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarBorrowerIndex; /// @dev The MOAR accrued but not yet transferred to each user mapping(address => uint) public moarAccrued; } contract MoartrollerV4Storage is MoartrollerV3Storage { // @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract MoartrollerV5Storage is MoartrollerV4Storage { /// @dev The portion of MOAR that each contributor receives per block mapping(address => uint) public moarContributorSpeeds; /// @dev Last block at which a contributor's MOAR rewards have been allocated mapping(address => uint) public lastContributorBlock; } contract MoartrollerV6Storage is MoartrollerV5Storage { /** * @dev Moar token address */ address public moarToken; /** * @dev MProxy address */ address public mProxy; /** * @dev CProtection contract which can be used for collateral optimisation */ MProtection public cprotection; /** * @dev Mapping for basic token address to mToken */ mapping(address => MToken) public tokenAddressToMToken; /** * @dev Math model for liquidity calculation */ LiquidityMathModelInterface public liquidityMathModel; /** * @dev Liquidation model for liquidation related functions */ LiquidationModelInterface public liquidationModel; /** * @dev List of addresses with privileged access */ mapping(address => uint) public privilegedAddresses; /** * @dev Determines if reward claim feature is enabled */ bool public rewardClaimEnabled; } // Copyright (c) 2020 The UNION Protocol Foundation // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /** * @title UNION Protocol Governance Token * @dev Implementation of the basic standard token. */ contract UnionGovernanceToken is AccessControl, IERC20 { using Address for address; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /** * @notice Struct for marking number of votes from a given block * @member from * @member votes */ struct VotingCheckpoint { uint256 from; uint256 votes; } /** * @notice Struct for locked tokens * @member amount * @member releaseTime * @member votable */ struct LockedTokens{ uint amount; uint releaseTime; bool votable; } /** * @notice Struct for EIP712 Domain * @member name * @member version * @member chainId * @member verifyingContract * @member salt */ struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; bytes32 salt; } /** * @notice Struct for EIP712 VotingDelegate call * @member owner * @member delegate * @member nonce * @member expirationTime */ struct VotingDelegate { address owner; address delegate; uint256 nonce; uint256 expirationTime; } /** * @notice Struct for EIP712 Permit call * @member owner * @member spender * @member value * @member nonce * @member deadline */ struct Permit { address owner; address spender; uint256 value; uint256 nonce; uint256 deadline; } /** * @notice Vote Delegation Events */ event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate); event VotingDelegateRemoved(address indexed _owner); /** * @notice Vote Balance Events * Emmitted when a delegate account's vote balance changes at the time of a written checkpoint */ event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance); /** * @notice Transfer/Allocator Events */ event TransferStatusChanged(bool _newTransferStatus); /** * @notice Reversion Events */ event ReversionStatusChanged(bool _newReversionSetting); /** * @notice EIP-20 Approval event */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice EIP-20 Transfer event */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Burn(address indexed _from, uint256 _value); event AddressPermitted(address indexed _account); event AddressRestricted(address indexed _account); /** * @dev AccessControl recognized roles */ bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE"); bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN"); bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT"); bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK"); bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED"); bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST"); bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 public constant DELEGATE_TYPEHASH = keccak256( "DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)" ); //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; address private constant BURN_ADDRESS = address(0); address public UPGT_CONTRACT_ADDRESS; /** * @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting. */ bytes32 public immutable EIP712DOMAIN_SEPARATOR; /** * @dev EIP-20 token name */ string public name = "UNION Protocol Governance Token"; /** * @dev EIP-20 token symbol */ string public symbol = "UNN"; /** * @dev EIP-20 token decimals */ uint8 public decimals = 18; /** * @dev Contract version */ string public constant version = '0.0.1'; /** * @dev Initial amount of tokens */ uint256 private uint256_initialSupply = 100000000000 * 10**18; /** * @dev Total amount of tokens */ uint256 private uint256_totalSupply; /** * @dev Chain id */ uint256 private uint256_chain_id; /** * @dev general transfer restricted as function of public sale not complete */ bool private b_canTransfer = false; /** * @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions. */ bool private b_revert = false; //false allows false return values /** * @dev Locked destinations list */ mapping(address => bool) private m_lockedDestinations; /** * @dev EIP-20 allowance and balance maps */ mapping(address => mapping(address => uint256)) private m_allowances; mapping(address => uint256) private m_balances; mapping(address => LockedTokens[]) private m_lockedBalances; /** * @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712 */ mapping(address => uint256) private m_nonces; /** * @dev delegated account may for off-line vote delegation */ mapping(address => address) private m_delegatedAccounts; /** * @dev delegated account inverse map is needed to live calculate voting power */ mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap; /** * @dev indexed mapping of vote checkpoints for each account */ mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints; /** * @dev mapping of account addrresses to voting checkpoints */ mapping(address => uint256) private m_accountVotingCheckpoints; /** * @dev Contructor for the token * @param _owner address of token contract owner * @param _initialSupply of tokens generated by this contract * Sets Transfer the total suppply to the owner. * Sets default admin role to the owner. * Sets ROLE_ALLOCATE to the owner. * Sets ROLE_GOVERN to the owner. * Sets ROLE_MINT to the owner. * Sets EIP 712 Domain Separator. */ constructor(address _owner, uint256 _initialSupply) public { //set internal contract references UPGT_CONTRACT_ADDRESS = address(this); //setup roles using AccessControl _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(ROLE_ADMIN, _owner); _setupRole(ROLE_ADMIN, _msgSender()); _setupRole(ROLE_ALLOCATE, _owner); _setupRole(ROLE_ALLOCATE, _msgSender()); _setupRole(ROLE_TRUSTED, _owner); _setupRole(ROLE_TRUSTED, _msgSender()); _setupRole(ROLE_GOVERN, _owner); _setupRole(ROLE_MINT, _owner); _setupRole(ROLE_LOCK, _owner); _setupRole(ROLE_TEST, _owner); m_balances[_owner] = _initialSupply; uint256_totalSupply = _initialSupply; b_canTransfer = false; uint256_chain_id = _getChainId(); EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({ name : name, version : version, chainId : uint256_chain_id, verifyingContract : address(this), salt : keccak256(abi.encodePacked(name)) } )); emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply); } /** * @dev Sets transfer status to lock token transfer * @param _canTransfer value can be true or false. * disables transfer when set to false and enables transfer when true * Only a member of ADMIN role can call to change transfer status */ function setCanTransfer(bool _canTransfer) public { if(hasRole(ROLE_ADMIN, _msgSender())){ b_canTransfer = _canTransfer; emit TransferStatusChanged(_canTransfer); } } /** * @dev Gets status of token transfer lock * @return true or false status of whether the token can be transfered */ function getCanTransfer() public view returns (bool) { return b_canTransfer; } /** * @dev Sets transfer reversion status to either return false or throw on error * @param _reversion value can be true or false. * disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true * Only a member of ADMIN role can call to change transfer reversion status */ function setReversion(bool _reversion) public { if(hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TEST, _msgSender()) ) { b_revert = _reversion; emit ReversionStatusChanged(_reversion); } } /** * @dev Gets status of token transfer reversion * @return true or false status of whether the token transfer failures return false or are reverted */ function getReversion() public view returns (bool) { return b_revert; } /** * @dev retrieve current chain id * @return chain id */ function getChainId() public pure returns (uint256) { return _getChainId(); } /** * @dev Retrieve current chain id * @return chain id */ function _getChainId() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Retrieve total supply of tokens * @return uint256 total supply of tokens */ function totalSupply() public view override returns (uint256) { return uint256_totalSupply; } /** * Balance related functions */ /** * @dev Retrieve balance of a specified account * @param _account address of account holding balance * @return uint256 balance of the specified account address */ function balanceOf(address _account) public view override returns (uint256) { return m_balances[_account].add(_calculateReleasedBalance(_account)); } /** * @dev Retrieve locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function lockedBalanceOf(address _account) public view returns (uint256) { return _calculateLockedBalance(_account); } /** * @dev Retrieve lenght of locked balance array for specific address * @param _account address of account holding locked balance * @return uint256 locked balance array lenght */ function getLockedTokensListSize(address _account) public view returns (uint256){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); return m_lockedBalances[_account].length; } /** * @dev Retrieve locked tokens struct from locked balance array for specific address * @param _account address of account holding locked tokens * @param _index index in array with locked tokens position * @return amount of locked tokens * @return releaseTime descibes time when tokens will be unlocked * @return votable flag is describing votability of tokens */ function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index"); LockedTokens storage lockedTokens = m_lockedBalances[_account][_index]; return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable); } /** * @dev Calculates locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function _calculateLockedBalance(address _account) private view returns (uint256) { uint256 lockedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime > block.timestamp){ lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount); } } return lockedBalance; } /** * @dev Calculates released balance of a specified account * @param _account address of account holding released balance * @return uint256 released balance of the specified account address */ function _calculateReleasedBalance(address _account) private view returns (uint256) { uint256 releasedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount); } } return releasedBalance; } /** * @dev Calculates locked votable balance of a specified account * @param _account address of account holding locked votable balance * @return uint256 locked votable balance of the specified account address */ function _calculateLockedVotableBalance(address _account) private view returns (uint256) { uint256 lockedVotableBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].votable == true){ lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount); } } return lockedVotableBalance; } /** * @dev Moves released balance to normal balance for a specified account * @param _account address of account holding released balance */ function _moveReleasedBalance(address _account) internal virtual{ uint256 releasedToMove = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount); m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1]; m_lockedBalances[_account].pop(); } } m_balances[_account] = m_balances[_account].add(releasedToMove); } /** * Allowance related functinons */ /** * @dev Retrieve the spending allowance for a token holder by a specified account * @param _owner Token account holder * @param _spender Account given allowance * @return uint256 allowance value */ function allowance(address _owner, address _spender) public override virtual view returns (uint256) { return m_allowances[_owner][_spender]; } /** * @dev Message sender approval to spend for a specified amount * @param _spender address of party approved to spend * @param _value amount of the approval * @return boolean success status * public wrapper for _approve, _owner is msg.sender */ function approve(address _spender, uint256 _value) public override returns (bool) { bool success = _approveUNN(_msgSender(), _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: APPROVE ERROR"); } return success; } /** * @dev Token owner approval of amount for specified spender * @param _owner address of party that owns the tokens being granted approval for spending * @param _spender address of party that is granted approval for spending * @param _value amount approved for spending * @return boolean approval status * if _spender allownace for a given _owner is greater than 0, * increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738 */ function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (m_allowances[_owner][_spender] == 0 || _value == 0) ){ m_allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); retval = true; } return retval; } /** * @dev Increase spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _addedValue specified incremental increase * @return boolean increaseAllowance status * public wrapper for _increaseAllowance, _owner restricted to msg.sender */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue); if(!success && b_revert){ revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to increase spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _addedValue specified incremental increase * @return boolean return value status * increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address. */ function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _addedValue > 0 ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * @dev Decrease spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _subtractedValue specified incremental decrease * @return boolean success status * public wrapper for _decreaseAllowance, _owner restricted to msg.sender */ //public wrapper for _decreaseAllowance, _owner restricted to msg.sender function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue); if(!success && b_revert){ revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to decrease spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _subtractedValue specified incremental decrease * @return boolean return value status * decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address. */ function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _subtractedValue > 0 && m_allowances[_owner][_spender] >= _subtractedValue ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * LockedDestination related functions */ /** * @dev Adds address as a designated destination for tokens when locked for allocation only * @param _address Address of approved desitnation for movement during lock * @return success in setting address as eligible for transfer independent of token lock status */ function setAsEligibleLockedDestination(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ m_lockedDestinations[_address] = true; retVal = true; } return retVal; } /** * @dev removes desitnation as eligible for transfer * @param _address address being removed */ function removeEligibleLockedDestination(address _address) public { if(hasRole(ROLE_ADMIN, _msgSender())){ require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); delete(m_lockedDestinations[_address]); } } /** * @dev checks whether a destination is eligible as recipient of transfer independent of token lock status * @param _address address being checked * @return whether desitnation is locked */ function checkEligibleLockedDesination(address _address) public view returns (bool) { return m_lockedDestinations[_address]; } /** * @dev Adds address as a designated allocator that can move tokens when they are locked * @param _address Address receiving the role of ROLE_ALLOCATE * @return success as true or false */ function setAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ grantRole(ROLE_ALLOCATE, _address); retVal = true; } return retVal; } /** * @dev Removes address as a designated allocator that can move tokens when they are locked * @param _address Address being removed from the ROLE_ALLOCATE * @return success as true or false */ function removeAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ if(hasRole(ROLE_ALLOCATE, _address)){ revokeRole(ROLE_ALLOCATE, _address); retVal = true; } } return retVal; } /** * @dev Checks to see if an address has the role of being an allocator * @param _address Address being checked for ROLE_ALLOCATE * @return true or false whether the address has ROLE_ALLOCATE assigned */ function checkAsAllocator(address _address) public view returns (bool) { return hasRole(ROLE_ALLOCATE, _address); } /** * Transfer related functions */ /** * @dev Public wrapper for transfer function to move tokens of specified value to a given address * @param _to specified recipient * @param _value amount being transfered to recipient * @return status of transfer success */ function transfer(address _to, uint256 _value) external override returns (bool) { bool success = _transferUNN(_msgSender(), _to, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER"); } return success; } /** * @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required. * @param _owner The address owner where transfer originates * @param _to The address to transfer to * @param _value The amount to be transferred * @return status of transfer success */ function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_to] = m_balances[_to].add(_value); retval = true; //need to move voting delegates with transfer of tokens retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value to a given address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){ bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); retval = true; //need to move voting delegates with transfer of tokens // retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferFrom function * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) { bool success = _transferFromUNN(_owner, _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM"); } return success; } /** * @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) { if( _spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_spender] = m_balances[_spender].add(_value); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer retval = retval && _moveVotingDelegates(_owner, _spender, _value); emit Transfer(_owner, _spender, _value); } } return retval; } /** * @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer // retval = retval && _moveVotingDelegates(_owner, _to, _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public function to burn tokens * @param _value number of tokens to be burned * @return whether tokens were burned * Only ROLE_MINTER may burn tokens */ function burn(uint256 _value) external returns (bool) { bool success = _burn(_value); if(!success && b_revert){ revert("UPGT_ERROR: FAILED TO BURN"); } return success; } /** * @dev Private function Burn tokens * @param _value number of tokens to be burned * @return bool whether the tokens were burned * only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet. */ function _burn(uint256 _value) internal returns (bool) { bool retval = false; if(hasRole(ROLE_MINT, _msgSender()) && (m_balances[_msgSender()] >= _value) ){ m_balances[_msgSender()] -= _value; uint256_totalSupply = uint256_totalSupply.sub(_value); retval = true; emit Burn(_msgSender(), _value); } return retval; } /** * Voting related functions */ /** * @dev Public wrapper for _calculateVotingPower function which calulates voting power * @dev voting power = balance + locked votable balance + delegations * @return uint256 voting power */ function calculateVotingPower() public view returns (uint256) { return _calculateVotingPower(_msgSender()); } /** * @dev Calulates voting power of specified address * @param _account address of token holder * @return uint256 voting power */ function _calculateVotingPower(address _account) private view returns (uint256) { uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account)); for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) { if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){ address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i); votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount)); } } return votingPower; } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful * Requires ROLE_TEST */ function moveVotingDelegates( address _source, address _destination, uint256 _amount) public returns (bool) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _moveVotingDelegates(_source, _destination, _amount); } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful */ function _moveVotingDelegates( address _source, address _destination, uint256 _amount ) internal returns (bool) { if(_source != _destination && _amount > 0) { if(_source != BURN_ADDRESS) { uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source]; uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0; if(sourceNumberOfVotingCheckpointsOriginal >= _amount) { uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount); _writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew); } } if(_destination != BURN_ADDRESS) { uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination]; uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0; uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount); _writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew); } } return true; } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Public function for writing voting checkpoint * Requires ROLE_TEST */ function writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) public { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); _writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes); } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Private function for writing voting checkpoint */ function _writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) internal { if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes; } else { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes); _numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1); } emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes); } /** * @dev Calculate account votes as of a specific block * @param _account address whose votes are counted * @param _blockNumber from which votes are being counted * @return number of votes counted */ function getVoteCountAtBlock( address _account, uint256 _blockNumber) public view returns (uint256) { uint256 voteCount = 0; if(_blockNumber < block.number) { if(m_accountVotingCheckpoints[_account] != 0) { if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) { voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes; } else if(m_votingCheckpoints[_account][0].from > _blockNumber) { voteCount = 0; } else { uint256 lower = 0; uint256 upper = m_accountVotingCheckpoints[_account].sub(1); while(upper > lower) { uint256 center = upper.sub((upper.sub(lower).div(2))); VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center]; if(votingCheckpoint.from == _blockNumber) { voteCount = votingCheckpoint.votes; break; } else if(votingCheckpoint.from < _blockNumber) { lower = center; } else { upper = center.sub(1); } } } } } return voteCount; } /** * @dev Vote Delegation Functions * @param _to address where message sender is assigning votes * @return success of message sender delegating vote * delegate function does not allow assignment to burn */ function delegateVote(address _to) public returns (bool) { return _delegateVote(_msgSender(), _to); } /** * @dev Delegate votes from token holder to another address * @param _from Token holder * @param _toDelegate Address that will be delegated to for purpose of voting * @return success as to whether delegation has been a success */ function _delegateVote( address _from, address _toDelegate) internal returns (bool) { bool retval = false; if(_toDelegate != BURN_ADDRESS) { address currentDelegate = m_delegatedAccounts[_from]; uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from)); address oldToDelegate = m_delegatedAccounts[_from]; m_delegatedAccounts[_from] = _toDelegate; m_delegatedAccountsInverseMap[oldToDelegate].remove(_from); if(_from != _toDelegate){ m_delegatedAccountsInverseMap[_toDelegate].add(_from); } retval = true; retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance); if(retval) { if(_from == _toDelegate){ emit VotingDelegateRemoved(_from); } else{ emit VotingDelegateChanged(_from, currentDelegate, _toDelegate); } } } return retval; } /** * @dev Revert voting delegate control to owner account * @param _account The account that has delegated its vote * @return success of reverting delegation to owner */ function _revertVotingDelegationToOwner(address _account) internal returns (bool) { return _delegateVote(_account, _account); } /** * @dev Used by an message sending account to recall its voting delegates * @return success of reverting delegation to owner */ function recallVotingDelegate() public returns (bool) { return _revertVotingDelegationToOwner(_msgSender()); } /** * @dev Retrieve the voting delegate for a specified account * @param _account The account that has delegated its vote */ function getVotingDelegate(address _account) public view returns (address) { return m_delegatedAccounts[_account]; } /** * EIP-712 related functions */ /** * @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit * @param _owner address of token owner * @param _spender address of designated spender * @param _value value permitted for spend * @param _deadline expiration of signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline)) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _approveUNN(_owner, _spender, _value); } /** * @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote * @param _owner address of token owner * @param _delegate address of voting delegate * @param _expiretimestamp expiration of delegation signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @ @return bool true or false depedening on whether vote was successfully delegated */ function delegateVoteBySignature( address _owner, address _delegate, uint256 _expiretimestamp, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, _hash(VotingDelegate( { owner : _owner, delegate : _delegate, nonce : m_nonces[_owner]++, expirationTime : _expiretimestamp }) ) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _delegateVote(_owner, _delegate); } /** * @dev Public hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain * Requires ROLE_TEST */ function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_eip712Domain); } /** * @dev Hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate * Requires ROLE_TEST */ function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_delegate); } /** * @dev Public hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit * Requires ROLE_TEST */ function hashPermit(Permit memory _permit) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_permit); } /** * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function * Requires ROLE_TEST */ function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _recoverSigner(_digest, _ecv, _ecr, _ecs); } /** * @dev Private hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain */ function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(_eip712Domain.name)), keccak256(bytes(_eip712Domain.version)), _eip712Domain.chainId, _eip712Domain.verifyingContract, _eip712Domain.salt ) ); } /** * @dev Private hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate */ function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) { return keccak256( abi.encode( DELEGATE_TYPEHASH, _delegate.owner, _delegate.delegate, _delegate.nonce, _delegate.expirationTime ) ); } /** * @dev Private hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit */ function _hash(Permit memory _permit) internal pure returns (bytes32) { return keccak256(abi.encode( PERMIT_TYPEHASH, _permit.owner, _permit.spender, _permit.value, _permit.nonce, _permit.deadline )); } /** * @dev Recover signer information from provided digest * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function */ function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) 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. if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if(_ecv != 27 && _ecv != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(_digest, _ecv, _ecr, _ecs); require(signer != BURN_ADDRESS, "ECDSA: invalid signature"); return signer; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../Interfaces/EIP20Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeEIP20 * @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. * This is a forked version of Openzeppelin's SafeERC20 contract but supporting * EIP20Interface instead of Openzeppelin's IERC20 * 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 SafeEIP20 { using SafeMath for uint256; using Address for address; function safeTransfer(EIP20Interface token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2; import "./PriceOracle.sol"; import "./MoartrollerInterface.sol"; pragma solidity ^0.6.12; interface LiquidationModelInterface { function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); struct LiquidateCalculateSeizeUserTokensArgumentsSet { PriceOracle oracle; MoartrollerInterface moartroller; address mTokenBorrowed; address mTokenCollateral; uint actualRepayAmount; address accountForLiquidation; uint liquidationIncentiveMantissa; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.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 {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)); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title MOAR's InterestRateModel Interface * @author MOAR */ interface InterestRateModelInterface { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721Upgradeable.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 _tokenOwners.contains(tokenId); } /** * @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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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 = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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; // 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]; } // 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); } // 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)))); } // 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface CopMappingInterface { function getTokenAddress() external view returns (address); function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint); function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address); function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256); function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint); function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @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.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // 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 SafeMathUpgradeable { /** * @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.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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 EnumerableSetUpgradeable { // 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]; } // 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); } // 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)))); } // 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // 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. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps 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) private 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) private 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) private 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) private 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) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @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(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // 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 IERC165Upgradeable { /** * @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.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/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * 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 { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @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 {_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) public view returns (bool) { return _roles[role].members.contains(account); } /** * @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 returns (uint256) { return _roles[role].members.length(); } /** * @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 returns (address) { return _roles[role].members.at(index); } /** * @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 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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _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 { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _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 granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { 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}. * ==== */ 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 { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // 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: 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: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/MErc20Interface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MErc20 Contract * @notice MTokens which wrap an EIP-20 underlying */ contract MErc20 is MToken, MErc20Interface { using SafeEIP20 for EIP20Interface; /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function init(address underlying_, Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // MToken initialize does the bulk of the work super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external override returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external override returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems mTokens 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(uint redeemAmount) external override returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @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(uint borrowAmount) external override returns (uint) { return borrowInternal(borrowAmount); } function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) { return borrowForInternal(borrower, borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower. * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param mTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral); return err; } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20Interface token) override external { require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token"); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(admin, balance); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external override returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal override view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. *` * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal override returns (uint) { EIP20Interface token = EIP20Interface(underlying); uint balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(from, address(this), amount); // Calculate the amount that was *actually* transferred uint balanceAfter = token.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal override { EIP20Interface token = EIP20Interface(underlying); token.safeTransfer(to, amount); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface MErc20Interface { /*** User contract ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function borrowFor(address payable borrower, uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); }
Increase spender allowance by specified incremental value _spender address of party that is granted approval for spending _addedValue specified incremental increase return boolean increaseAllowance status public wrapper for _increaseAllowance, _owner restricted to msg.sender/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue); if(!success && b_revert){ revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR"); } return success; }
11,818,527
./partial_match/1/0x1058fba8E10C1dF675C79Ab988c18275F6337051/sources/HolyPool.sol
only yield to be redistributed should be present on this contract in baseAsset (or other tokens if swap fees) so no access to lp tokens for the funds invested
function setYieldDistributor(address _tokenAddress, address _distributorAddress) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only"); yieldDistributorAddress = _distributorAddress; IERC20(_tokenAddress).approve(_distributorAddress, ALLOWANCE_SIZE); }
3,937,544
./partial_match/1/0xF5F850daDdc393CE325D8ac395519224F498460F/sources/DFDComptroller.sol
Balancer swap function
interface Uni { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter); }
2,882,667
./partial_match/3/0xc8C2880FA38400DDFf59519C184F151eC7eF9d27/sources/FourConnect.sol
Just for funding purposes
function() public payable { }
5,316,961
pragma solidity ^0.4.24; import "./queue.sol"; import "./login.sol"; contract assign is login,queue{ struct arbitration { mapping(address => uint) flag; //flag为仲裁师对某订单的评估状态,当评估后,该状态flag=1,不允许再次评估 uint tick; uint sum; } mapping(address => uint) values; //评估师报价 mapping(address => uint) loads; //评估师负载 mapping(address => uint[]) record; //记录评估师下评估单编号 mapping(address => uint[]) appeallist; //记录每个仲裁者名下的仲裁单 mapping(uint => arbitration) status; //记录仲裁者对某个评估单的评估结果 mapping(uint => address[]) incomelist; //记录每个申诉单对应的仲裁师评估序列 Queue Leaderboard; //排行榜字段(最大接受100个订单,超过后先进先出) constructor() public { Leaderboard.data.length = 200; } /** * guobin * 录入评估师报价 */ function _Enter_quote(uint value) internal { values[msg.sender] = value; } /** * guobin * 返回评估师报价 */ function _check_quote(address work) internal view returns (uint) { if(values[work] >= 100) { return (values[work]-100); } else { return 0; } } /** * guobin * 计算评估师竞争力 */ function calc(address worker,uint state) internal view returns (uint competitve) { uint Load = loads[worker]; if(Load >= 5) { return 0; } if(state == 0) { //创建评估单分配时计算公式 //真实公式:competitve = check_balance(worker) * (2 - values[worker]/10) * (1 - length(loads[worker])/5); competitve = check_balance(worker) * (values[worker]) * (5 - Load); } else { //评估单被退回时计算公式 competitve = check_balance(worker) * (5 - Load); } } /** * guobin * 统计并筛选出最优评估师 */ function statistic(uint state) internal view returns (address choose) { uint256 max = 0; uint256 current = 0; for(uint i = 0;i < workers.length;i++) { current = calc(workers[i],state); if(current > max) { max = current; choose = workers[i]; } } } /** * guobin * 将当前订单编号分配给最优评估师 */ function distribution(uint number,address choose) internal returns (uint) { loads[choose] += 1; _setassessor(number,choose); //存储评估单对应的评估师 uint[] memory tmp = record[choose]; for(uint i = 0;i < tmp.length;i++) { if(tmp[i] == number) return 0; } record[choose].push(number); //将当前评估单编号(由js传递)存入对应评估师地址 } /** * guobin * 返回当前评估师的所有评估单编号 */ function _backvalnumber() view internal returns (uint[]) { return record[msg.sender]; } /** * guobin * 评估师对订单进行评估 */ function _evaluate(uint index,uint value) internal { uint tokentmp = _check_quote(msg.sender); order.store_msg[index].Evaluation = value; order.store_sta[index].Evaluation_status = "1"; //将评估单状态改为已评估 finishwork(index,0); reward(msg.sender,tokentmp); //根据评估师设定的分成比例给予通证奖励 msg.sender.transfer(100-tokentmp); //根据评估师设定的分成比例给予ether奖励 push(Leaderboard,index); //将评估后的工单推入排行榜公示,只有评估后的订单才可进入排行榜 } /** * guobin * 将申诉订单编号分配给仲裁者 */ function _appealdistribution(uint number,address appeal1,address appeal2,address appeal3,address appeal4,address appeal5) internal { loads[appeal1] += 1; loads[appeal2] += 1; loads[appeal3] += 1; loads[appeal4] += 1; loads[appeal5] += 1; appeallist[appeal1].push(number); //将当前评估单编号(由js传递)存入对应仲裁者地址 appeallist[appeal2].push(number); //将当前评估单编号(由js传递)存入对应仲裁者地址 appeallist[appeal3].push(number); //将当前评估单编号(由js传递)存入对应仲裁者地址 appeallist[appeal4].push(number); //将当前评估单编号(由js传递)存入对应仲裁者地址 appeallist[appeal5].push(number); //将当前评估单编号(由js传递)存入对应仲裁者地址 order.store_sta[number].Evaluation_status = "2"; //将评估单状态改为已申诉 } /** * guobin * 返回排行榜中所有评估单编号 */ function _backLeaderboard() internal view returns (uint[]) { return Leaderboard.data; } /** * guobin * 返回排行榜中所有评估单编号 */ function _backLength() internal view returns (uint) { return length(Leaderboard); } /** * guobin * 返回当前仲裁者的所有评估单编号 */ function _backappnumber() internal view returns (uint[]) { return appeallist[msg.sender]; } /** * guobin * 当前仲裁者对本订单是否具备仲裁条件 */ function _appealesituation(uint index) internal view returns (uint) { if(status[index].flag[msg.sender] == 1) { return 0; //返回0,则不具备仲裁条件 } else { return 1; //返回1,具备仲裁条件 } } /** * guobin * 仲裁者对订单进行评估 */ function _appealevaluate(uint index,uint value) internal returns (uint) { uint tmpvalue = 0; uint tmpsum = 0; if(status[index].flag[msg.sender] == 1) { //当同一仲裁师再次进入同一评估单,不再允许进行评估 revert(); } loads[msg.sender] -= 1; //当前仲裁师评估订单,工作负载减1 incomelist[index].push(msg.sender); //当前仲裁师评估订单,记录其订单评估顺序(方便做收益分配) status[index].tick += 1; //当前申诉单tick记录加1,共5人(即最大值为5) status[index].sum += value; //将当前仲裁师对申诉单的估价累加进sum status[index].flag[msg.sender] = 1; //当前仲裁师进入本函数,其flag状态从false变true,下次不可再进入 if(status[index].tick == 5) { tmpvalue = order.store_msg[index].Evaluation * 500; //评估师估价(评估价*5*100) tmpsum = status[index].sum; //5个仲裁者的估价总数 order.store_sta[index].Evaluation_status = "3"; //将评估单状态改为已仲裁 if(tmpvalue > tmpsum * 95) { if(tmpvalue < tmpsum * 105) { _resultprocessing(index,100,0); //仲裁结果:合理,平台给予仲裁者通证奖励 return 0; //返回1,代表评估师对于订单的价格估价是合理的 } else { order.store_msg[index].Evaluation = tmpsum/5; //将仲裁师的平均估价重新赋给Evaluation _resultprocessing(index,2*_check_quote(_getassessor(index)),1); //仲裁结果:不合理,平台双倍(2倍)扣除该评估师获得该订单的通证奖励给予仲裁师(有可能多于100,有可能少于100,取决于评估师获得的通证数量) return 1; //评估师价格高于仲裁师平均估价105%,代表评估师对订单估价不合理 } } else { order.store_msg[index].Evaluation = tmpsum/5; //将仲裁师的平均估价重新赋给Evaluation _resultprocessing(index,2*_check_quote(_getassessor(index)),1); return 1; //评估师价格低于仲裁师平均估价95%,代表评估师对订单估价不合理 } } } /** * guobin * 仲裁结果:合理/不合理,处理流程 */ function _resultprocessing(uint index,uint amount,uint state) internal { uint total = 0; uint[5] memory appeal_val; uint[5] memory pay; address[5] memory appeal; for(uint i = 0;i < 5;i++) { appeal[i] = incomelist[index][i]; appeal_val[i] = (5-i) * check_balance(appeal[i]); total += appeal_val[i]; } for(i = 0;i < 5;i++) { pay[i] = amount*(appeal_val[i] / total); reward(appeal[i],pay[i]); } if(state == 1) { punish(_getassessor(index),amount); } } /** * guobin * 仲裁订单进度查询 */ function _appealeschedule(uint index) internal view returns (uint) { return status[index].tick; } /** * guobin * 完成当前订单 */ function finishwork(uint index,uint parameter) internal{ if(parameter == 1) { //当评估单被两次退回后,自动变为已关闭状态 order.store_sta[index].Evaluation_status = "4"; //将评估单状态改为已关闭 } loads[msg.sender] -= 1; } }
guobin 返回排行榜中所有评估单编号/
function _backLeaderboard() internal view returns (uint[]) { return Leaderboard.data; }
12,887,957
pragma solidity 0.8.2; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IController.sol"; import "./interfaces/INeuronPool.sol"; import "./interfaces/INeuronPoolConverter.sol"; import "./interfaces/IOneSplitAudit.sol"; import "./interfaces/IStrategy.sol"; import "./interfaces/IConverter.sol"; // Deployed once (in contrast with nPools - those are created individually for each strategy). // Then new nPools are added via setNPool function contract Controller { 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 nPools; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public approvedNPoolConverters; uint256 public split = 500; uint256 public constant max = 10000; constructor( address _governance, address _strategist, address _timelock, address _devfund, address _treasury ) { 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"); require(_split <= max, "numerator cannot be greater than denominator"); 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 setNPool(address _token, address _nPool) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(nPools[_token] == address(0), "nPool"); nPools[_token] = _nPool; } function approveNPoolConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedNPoolConverters[_converter] = true; } function revokeNPoolConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedNPoolConverters[_converter] = false; } // Called before adding strategy to controller, turns the strategy 'on-off' // We're in need of an additional array for strategies' on-off states (are we?) // Called when deploying function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } // Turns off/revokes strategy function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); require( strategies[_token] != _strategy, "cannot revoke active strategy" ); approvedStrategies[_token][_strategy] = false; } function setConvenienceFee(uint256 _convenienceFee) external { require(msg.sender == timelock, "!timelock"); convenienceFee = _convenienceFee; } // Adding or updating a strategy 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; } // Depositing token to a pool function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; // Token needed for strategy address _want = IStrategy(_strategy).want(); if (_want != _token) { // Convert if token other than wanted deposited address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = IConverter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { // Transferring to the strategy address IERC20(_token).safeTransfer(_strategy, _amount); } // Calling deposit @ strategy 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, ) = IOneSplitAudit(onesplit).getExpectedReturn( _token, _want, _balance, parts, 0 ); } // Only allows to withdraw non-core strategy tokens and send to treasury ~ 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) = IOneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); IOneSplitAudit(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 == nPools[_token], "!nPool"); IStrategy(strategies[_token]).withdraw(_amount); } // Function to swap between nPools // Seems to be called when a new version of NPool is created // With NPool functioning, unwanted tokens are sometimes landing here; this function helps transfer them to another pool // A transaction example https://etherscan.io/tx/0xc6f15e55f8520bc22a0bb9ac15b6f3fd80a0295e5c40b0e255eb7f3be34733f2 // https://etherscan.io/txs?a=0x6847259b2B3A4c17e7c43C54409810aF48bA5210&ps=100&p=3 - Pickle's transaction calls // Last called ~140 days ago // Seems to be the culprit of recent Pickle's attack https://twitter.com/n2ckchong/status/1330244058669850624?lang=en // Googling the function returns some hack explanations https://halborn.com/category/explained-hacks/ // >The problem with this function is that it doesn’t check the validity of the nPools presented to it function swapExactNPoolForNPool( address _fromNPool, // From which NPool address _toNPool, // To which NPool uint256 _fromNPoolAmount, // How much nPool tokens to swap uint256 _toNPoolMinAmount, // How much nPool tokens you'd like at a minimum address payable[] calldata _targets, // targets - converters' contract addresses 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(approvedNPoolConverters[_targets[i]], "!converter"); } address _fromNPoolToken = INeuronPool(_fromNPool).token(); address _toNPoolToken = INeuronPool(_toNPool).token(); // Get pTokens from msg.sender IERC20(_fromNPool).safeTransferFrom( msg.sender, address(this), _fromNPoolAmount ); // Calculate how much underlying // is the amount of pTokens worth uint256 _fromNPoolUnderlyingAmount = _fromNPoolAmount .mul(INeuronPool(_fromNPool).getRatio()) .div(10**uint256(INeuronPool(_fromNPool).decimals())); // Call 'withdrawForSwap' on NPool's current strategy if NPool // doesn't have enough initial capital. // This has moves the funds from the strategy to the NPool's // 'earnable' amount. Enabling 'free' withdrawals uint256 _fromNPoolAvailUnderlying = IERC20(_fromNPoolToken).balanceOf( _fromNPool ); if (_fromNPoolAvailUnderlying < _fromNPoolUnderlyingAmount) { IStrategy(strategies[_fromNPoolToken]).withdrawForSwap( _fromNPoolUnderlyingAmount.sub(_fromNPoolAvailUnderlying) ); } // Withdraw from NPool // Note: this is free since its still within the "earnable" amount // as we transferred the access IERC20(_fromNPool).safeApprove(_fromNPool, 0); IERC20(_fromNPool).safeApprove(_fromNPool, _fromNPoolAmount); INeuronPool(_fromNPool).withdraw(_fromNPoolAmount); // Calculate fee uint256 _fromUnderlyingBalance = IERC20(_fromNPoolToken).balanceOf( address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance .mul(convenienceFee) .div(convenienceFeeMax); if (_convenienceFee > 1) { IERC20(_fromNPoolToken).safeTransfer( devfund, _convenienceFee.div(2) ); IERC20(_fromNPoolToken).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 NPool uint256 _toBal = IERC20(_toNPoolToken).balanceOf(address(this)); IERC20(_toNPoolToken).safeApprove(_toNPool, 0); IERC20(_toNPoolToken).safeApprove(_toNPool, _toBal); INeuronPool(_toNPool).deposit(_toBal); // Send NPool Tokens to user uint256 _toNPoolBal = INeuronPool(_toNPool).balanceOf(address(this)); if (_toNPoolBal < _toNPoolMinAmount) { revert("!min-nPool-amount"); } INeuronPool(_toNPool).transfer(msg.sender, _toNPoolBal); return _toNPoolBal; } 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) } } } } // SPDX-License-Identifier: MIT 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 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 {} } // 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; // 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; } } } // 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.2; interface IController { function nPools(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; } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface INeuronPool is IERC20 { function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function depositAll() external; function deposit(uint256) external; function withdrawAll() external; function withdraw(uint256) external; function earn() external; function decimals() external view returns (uint8); } pragma solidity 0.8.2; interface INeuronPoolConverter { function convert( address _refundExcess, // address to send the excess amount when adding liquidity uint256 _amount, // UNI LP Amount bytes calldata _data ) external returns (uint256); } pragma solidity 0.8.2; interface IOneSplitAudit { 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; } pragma solidity 0.8.2; 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); } pragma solidity 0.8.2; interface IConverter { function convert(address) external returns (uint256); } // 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) { return msg.data; } } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/INeuronPool.sol"; import "../interfaces/IStEth.sol"; import "../interfaces/IWETH.sol"; import "../interfaces/ICurve.sol"; import "../interfaces/IUniswapRouterV2.sol"; import "../interfaces/IController.sol"; import "./StrategyBase.sol"; contract StrategyCurveSteCrv is StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Curve IStEth public constant stEth = IStEth(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84); // lido stEth IERC20 public constant steCRV = IERC20(0x06325440D014e39736583c165C2963BA99fAf14E); // ETH-stETH curve lp // Curve DAO ICurveGauge public gauge = ICurveGauge(0x182B723a58739a9c974cFDB385ceaDb237453c28); // stEthGauge ICurveFi public curve = ICurveFi(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022); // stEthSwap address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // Tokens we're farming IERC20 public constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 public constant ldo = IERC20(0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32); // How much CRV tokens to keep uint256 public keepCRV = 500; uint256 public keepCRVMax = 10000; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyBase( address(steCRV), _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { steCRV.approve(address(gauge), type(uint256).max); stEth.approve(address(curve), type(uint256).max); ldo.safeApprove(address(univ2Router2), type(uint256).max); crv.approve(address(univ2Router2), type(uint256).max); } // Swap for ETH receive() external payable {} // **** Getters **** function balanceOfPool() public view override returns (uint256) { return gauge.balanceOf(address(this)); } function getName() external pure override returns (string memory) { return "StrategyCurveStETH"; } function getHarvestable() external view returns (uint256) { return gauge.claimable_reward(address(this), address(crv)); } function getHarvestableEth() external view returns (uint256) { uint256 claimableLdo = gauge.claimable_reward( address(this), address(ldo) ); uint256 claimableCrv = gauge.claimable_reward( address(this), address(crv) ); return _estimateSell(address(crv), claimableCrv).add( _estimateSell(address(ldo), claimableLdo) ); } function _estimateSell(address currency, uint256 amount) internal view returns (uint256 outAmount) { address[] memory path = new address[](2); path[0] = currency; path[1] = weth; uint256[] memory amounts = IUniswapRouterV2(univ2Router2).getAmountsOut( amount, path ); outAmount = amounts[amounts.length - 1]; return outAmount; } // **** 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) { gauge.deposit(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { gauge.withdraw(_amount); return _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. gauge.claim_rewards(); ICurveMintr(mintr).mint(address(gauge)); uint256 _ldo = ldo.balanceOf(address(this)); uint256 _crv = crv.balanceOf(address(this)); if (_crv > 0) { _swapToNeurAndDistributePerformanceFees(address(crv), sushiRouter); } if (_ldo > 0) { _swapToNeurAndDistributePerformanceFees(address(ldo), sushiRouter); } _ldo = ldo.balanceOf(address(this)); _crv = 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); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } // How much CRV to swap? _crv = _crv.sub(_keepCRV); _swapUniswap(address(crv), weth, _crv); } if (_ldo > 0) { _swapUniswap(address(ldo), weth, _ldo); } IWETH(weth).withdraw(IWETH(weth).balanceOf(address(this))); uint256 _eth = address(this).balance; stEth.submit{value: _eth / 2}(strategist); _eth = address(this).balance; uint256 _stEth = stEth.balanceOf(address(this)); uint256[2] memory liquidity; liquidity[0] = _eth; liquidity[1] = _stEth; curve.add_liquidity{value: _eth}(liquidity, 0); // We want to get back sCRV deposit(); } } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface IStEth is IERC20 { function submit(address) external payable returns (uint256); } pragma solidity 0.8.2; interface IWETH { 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); } pragma solidity 0.8.2; interface ICurveFi { function add_liquidity( // stETH pool uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function balances(int128) external view 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 add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external payable; 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 to manage Crv strategies' interactions 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 claimable_reward(address, address) 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 ICurveFi_Polygon_3 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount, bool use_underlying ) 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_Polygon_2 { function A() external view returns (uint256); function A_precise() external view returns (uint256); function dynamic_fee(int128 i, int128 j) external view returns (uint256); function balances(uint256 i) external view returns (uint256); function get_virtual_price() external view returns (uint256); function calc_token_amount(uint256[2] calldata _amounts, bool is_deposit) external view returns (uint256); function add_liquidity(uint256[2] calldata _amounts, uint256 _min_mint_amount) external returns (uint256); function add_liquidity( uint256[2] calldata _amounts, uint256 _min_mint_amount, bool _use_underlying ) external returns (uint256); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external returns (uint256); function remove_liquidity(uint256 _amount, uint256[2] calldata _min_amounts) external returns (uint256[2] calldata); function remove_liquidity( uint256 _amount, uint256[2] calldata _min_amounts, bool _use_underlying ) external returns (uint256[2] calldata); function remove_liquidity_imbalance( uint256[2] calldata _amounts, uint256 _max_burn_amount ) external returns (uint256); function remove_liquidity_imbalance( uint256[2] calldata _amounts, uint256 _max_burn_amount, bool _use_underlying ) external returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount ) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 _min_amount, bool _use_underlying ) external returns (uint256); function ramp_A(uint256 _future_A, uint256 _future_time) external; function stop_ramp_A() external; function commit_new_fee( uint256 new_fee, uint256 new_admin_fee, uint256 new_offpeg_fee_multiplier ) external; function apply_new_fee() external; function revert_new_parameters() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function withdraw_admin_fees() external; function donate_admin_fees() external; function kill_me() external; function unkill_me() external; function set_aave_referral(uint256 referral_code) external; function set_reward_receiver(address _reward_receiver) external; function set_admin_fee_receiver(address _admin_fee_receiver) external; function coins(uint256 arg0) external view returns (address); function underlying_coins(uint256 arg0) external view returns (address); function admin_balances(uint256 arg0) external view returns (uint256); function fee() external view returns (uint256); function offpeg_fee_multiplier() external view returns (uint256); function admin_fee() external view returns (uint256); function owner() external view returns (address); function lp_token() external view returns (address); function initial_A() external view returns (uint256); function future_A() external view returns (uint256); function initial_A_time() external view returns (uint256); function future_A_time() external view returns (uint256); function admin_actions_deadline() external view returns (uint256); function transfer_ownership_deadline() external view returns (uint256); function future_fee() external view returns (uint256); function future_admin_fee() external view returns (uint256); function future_offpeg_fee_multiplier() external view returns (uint256); function future_owner() external view returns (address); function reward_receiver() external view returns (address); function admin_fee_receiver() external view returns (address); } pragma solidity 0.8.2; interface IUniswapRouterV2 { 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); } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/INeuronPool.sol"; import "../interfaces/IStakingRewards.sol"; import "../interfaces/IUniswapRouterV2.sol"; import "../interfaces/IController.sol"; // Strategy Contract Basics abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees - start with 30% uint256 public performanceTreasuryFee = 3000; uint256 public constant performanceTreasuryMax = 10000; // Withdrawal fee 0% // - 0% to treasury // - 0% to dev fund uint256 public withdrawalTreasuryFee = 0; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 0; uint256 public constant withdrawalDevFundMax = 100000; // Tokens // Input token accepted by the contract address public immutable neuronTokenAddress; address public immutable want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public constant univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public constant sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; mapping(address => bool) public harvesters; constructor( // Input token accepted by the contract address _want, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_neuronTokenAddress != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; neuronTokenAddress = _neuronTokenAddress; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent() { require( harvesters[msg.sender] || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view virtual returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external pure virtual returns (string memory); // **** Setters **** // function whitelistHarvester(address _harvester) external { require( msg.sender == governance || msg.sender == strategist, "not authorized" ); harvesters[_harvester] = true; } function revokeHarvester(address _harvester) external { require( msg.sender == governance || msg.sender == strategist, "not authorized" ); harvesters[_harvester] = false; } 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 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 pool 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 _nPool = IController(controller).nPools(address(want)); require(_nPool != address(0), "!nPool"); // additional protection so we don't burn the funds IERC20(want).safeTransfer( _nPool, _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 _nPool = IController(controller).nPools(address(want)); require(_nPool != address(0), "!nPool"); IERC20(want).safeTransfer(_nPool, 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 _nPool = IController(controller).nPools(address(want)); require(_nPool != address(0), "!nPool"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_nPool, 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)); 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; } IUniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapUniswapWithPath(address[] memory path, uint256 _amount) internal { require(path[1] != address(0)); IUniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapSushiswap( address _from, address _to, uint256 _amount ) internal { 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; } IUniswapRouterV2(sushiRouter).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapWithUniLikeRouter( address routerAddress, address _from, address _to, uint256 _amount ) internal returns (bool) { require(_to != address(0)); require( routerAddress != address(0), "_swapWithUniLikeRouter routerAddress cant be zero" ); 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; } try IUniswapRouterV2(routerAddress).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ) { return true; } catch { return false; } } function _swapSushiswapWithPath(address[] memory path, uint256 _amount) internal { require(path[1] != address(0)); IUniswapRouterV2(sushiRouter).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapToNeurAndDistributePerformanceFees( address swapToken, address swapRouterAddress ) internal { uint256 swapTokenBalance = IERC20(swapToken).balanceOf(address(this)); if (swapTokenBalance > 0 && performanceTreasuryFee > 0) { uint256 performanceTreasuryFeeAmount = swapTokenBalance .mul(performanceTreasuryFee) .div(performanceTreasuryMax); uint256 totalFeeAmout = performanceTreasuryFeeAmount; _swapAmountToNeurAndDistributePerformanceFees( swapToken, totalFeeAmout, swapRouterAddress ); } } function _swapAmountToNeurAndDistributePerformanceFees( address swapToken, uint256 amount, address swapRouterAddress ) internal { uint256 swapTokenBalance = IERC20(swapToken).balanceOf(address(this)); require( swapTokenBalance >= amount, "Amount is bigger than token balance" ); IERC20(swapToken).safeApprove(swapRouterAddress, 0); IERC20(weth).safeApprove(swapRouterAddress, 0); IERC20(swapToken).safeApprove(swapRouterAddress, amount); IERC20(weth).safeApprove(swapRouterAddress, type(uint256).max); bool isSuccesfullSwap = _swapWithUniLikeRouter( swapRouterAddress, swapToken, neuronTokenAddress, amount ); if (isSuccesfullSwap) { uint256 neuronTokenBalance = IERC20(neuronTokenAddress).balanceOf( address(this) ); if (neuronTokenBalance > 0) { // Treasury fees // Sending strategy's tokens to treasury. Initially @ 30% (set by performanceTreasuryFee constant) of strategy's assets IERC20(neuronTokenAddress).safeTransfer( IController(controller).treasury(), neuronTokenBalance ); } } else { // If failed swap to Neuron just transfer swap token to treasury IERC20(swapToken).safeApprove(IController(controller).treasury(), 0); IERC20(swapToken).safeApprove(IController(controller).treasury(), amount); IERC20(swapToken).safeTransfer( IController(controller).treasury(), amount ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; 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; } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./StrategyBase.sol"; import "../interfaces/ISushiChef.sol"; abstract contract StrategySushiFarmBaseCustomHarvest is StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Token addresses address public constant sushi = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; address public constant masterChef = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; // WETH/<token1> pair address public token1; // How much SUSHI tokens to keep? uint256 public keepSUSHI = 0; uint256 public constant keepSUSHIMax = 10000; uint256 public poolId; constructor( address _token1, uint256 _poolId, address _lp, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyBase( _lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { poolId = _poolId; token1 = _token1; IERC20(sushi).safeApprove(sushiRouter, type(uint256).max); IERC20(weth).safeApprove(sushiRouter, type(uint256).max); } function balanceOfPool() public view override returns (uint256) { (uint256 amount, ) = ISushiChef(masterChef).userInfo( poolId, address(this) ); return amount; } function getHarvestable() external view returns (uint256) { return ISushiChef(masterChef).pendingSushi(poolId, address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(masterChef, 0); IERC20(want).safeApprove(masterChef, _want); ISushiChef(masterChef).deposit(poolId, _want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ISushiChef(masterChef).withdraw(poolId, _amount); return _amount; } // **** Setters **** function setKeepSUSHI(uint256 _keepSUSHI) external { require(msg.sender == timelock, "!timelock"); keepSUSHI = _keepSUSHI; } } pragma solidity 0.8.2; // interface for Sushiswap MasterChef contract interface ISushiChef { 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 pendingSushi(uint256 _pid, address _user) external view returns (uint256); function sushi() external view returns (address); function sushiPerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accsushiPerShare ); 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 setsushiPerBlock(uint256 _sushiPerBlock) 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; } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./StrategyBase.sol"; import "../interfaces/ISushiChef.sol"; abstract contract StrategySushiFarmBase is StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Token addresses address public constant sushi = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; address public constant masterChef = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; // WETH/<token1> pair address public token1; // How much SUSHI tokens to keep? uint256 public keepSUSHI = 0; uint256 public constant keepSUSHIMax = 10000; uint256 public poolId; constructor( address _token1, uint256 _poolId, address _lp, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyBase( _lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { poolId = _poolId; token1 = _token1; IERC20(sushi).safeApprove(sushiRouter, type(uint256).max); IERC20(weth).safeApprove(sushiRouter, type(uint256).max); } function balanceOfPool() public view override returns (uint256) { (uint256 amount, ) = ISushiChef(masterChef).userInfo( poolId, address(this) ); return amount; } function getHarvestable() external view returns (uint256) { return ISushiChef(masterChef).pendingSushi(poolId, address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(masterChef, 0); IERC20(want).safeApprove(masterChef, _want); ISushiChef(masterChef).deposit(poolId, _want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ISushiChef(masterChef).withdraw(poolId, _amount); return _amount; } // **** Setters **** function setKeepSUSHI(uint256 _keepSUSHI) external { require(msg.sender == timelock, "!timelock"); keepSUSHI = _keepSUSHI; } // **** 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 SUSHI tokens ISushiChef(masterChef).deposit(poolId, 0); uint256 _sushi = IERC20(sushi).balanceOf(address(this)); if (_sushi > 0) { _swapToNeurAndDistributePerformanceFees(sushi, sushiRouter); } _sushi = IERC20(sushi).balanceOf(address(this)); if (_sushi > 0) { // 10% is locked up for future gov uint256 _keepSUSHI = _sushi.mul(keepSUSHI).div(keepSUSHIMax); IERC20(sushi).safeTransfer( IController(controller).treasury(), _keepSUSHI ); uint256 _swap = _sushi.sub(_keepSUSHI); IERC20(sushi).safeApprove(sushiRouter, 0); IERC20(sushi).safeApprove(sushiRouter, _swap); _swapSushiswap(sushi, weth, _swap); } // Swap half WETH for token1 uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapSushiswap(weth, token1, _weth.div(2)); } // Adds in liquidity for ETH/token1 _weth = IERC20(weth).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_weth > 0 && _token1 > 0) { IERC20(token1).safeApprove(sushiRouter, 0); IERC20(token1).safeApprove(sushiRouter, _token1); IUniswapRouterV2(sushiRouter).addLiquidity( weth, token1, _weth, _token1, 0, 0, address(this), block.timestamp + 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)) ); } deposit(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategySushiFarmBase.sol"; contract StrategySushiEthWbtcLp is StrategySushiFarmBase { // Token/ETH pool id in MasterChef contract uint256 public constant sushi_wbtc_poolId = 21; // Token addresses address public constant sushi_eth_wbtc_lp = 0xCEfF51756c56CeFFCA006cD410B03FFC46dd3a58; address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiFarmBase( wbtc, sushi_wbtc_poolId, sushi_eth_wbtc_lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategySushiEthWbtcLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategySushiFarmBase.sol"; contract StrategySushiEthUsdcLp is StrategySushiFarmBase { // Token/ETH pool id in MasterChef contract uint256 public constant sushi_usdc_poolId = 1; // Token addresses address public constant sushi_eth_usdc_lp = 0x397FF1542f962076d0BFE58eA045FfA2d347ACa0; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiFarmBase( usdc, sushi_usdc_poolId, sushi_eth_usdc_lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategySushiEthUsdcLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./StrategyFeiFarmBase.sol"; contract StrategyFeiTribeLp is StrategyFeiFarmBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Token addresses address public constant fei_rewards = 0x18305DaAe09Ea2F4D51fAa33318be5978D251aBd; address public constant uni_fei_tribe_lp = 0x9928e4046d7c6513326cCeA028cD3e7a91c7590A; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyFeiFarmBase( fei_rewards, uni_fei_tribe_lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategyFeiTribeLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategyStakingRewardsBase.sol"; abstract contract StrategyFeiFarmBase is StrategyStakingRewardsBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Token addresses address public constant fei = 0x956F47F50A910163D8BF957Cf5846D573E7f87CA; address public constant tribe = 0xc7283b66Eb1EB5FB86327f08e1B5816b0720212B; // How much TRIBE tokens to keep? uint256 public keepTRIBE = 0; uint256 public constant keepTRIBEMax = 10000; // Uniswap swap paths address[] public tribe_fei_path; constructor( address _rewards, address _lp, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyStakingRewardsBase( _rewards, _lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { tribe_fei_path = new address[](2); tribe_fei_path[0] = tribe; tribe_fei_path[1] = fei; IERC20(fei).approve(univ2Router2, type(uint256).max); IERC20(tribe).approve(univ2Router2, type(uint256).max); } // **** Setters **** function setKeepTRIBE(uint256 _keepTRIBE) external { require(msg.sender == timelock, "!timelock"); keepTRIBE = _keepTRIBE; } // **** 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 TRIBE tokens IStakingRewards(rewards).getReward(); uint256 _tribe = IERC20(tribe).balanceOf(address(this)); uint256 _fei = IERC20(fei).balanceOf(address(this)); if (_tribe > 0 && performanceTreasuryFee > 0) { uint256 tribePerfomanceFeeAmount = _tribe .mul(performanceTreasuryFee) .div(performanceTreasuryMax); _swapUniswapWithPath(tribe_fei_path, tribePerfomanceFeeAmount); _fei = IERC20(fei).balanceOf(address(this)); _swapAmountToNeurAndDistributePerformanceFees( fei, _fei, sushiRouter ); } _tribe = IERC20(tribe).balanceOf(address(this)); if (_tribe > 0 && performanceTreasuryFee > 0) { // 10% is locked up for future gov uint256 _keepTRIBE = _tribe.mul(keepTRIBE).div(keepTRIBEMax); IERC20(tribe).safeTransfer( IController(controller).treasury(), _keepTRIBE ); _tribe = _tribe.sub(_keepTRIBE); _swapUniswapWithPath(tribe_fei_path, _tribe.div(2)); } // Adds in liquidity for FEI/TRIBE _fei = IERC20(fei).balanceOf(address(this)); _tribe = IERC20(tribe).balanceOf(address(this)); if (_fei > 0 && _tribe > 0) { IUniswapRouterV2(univ2Router2).addLiquidity( fei, tribe, _fei, _tribe, 0, 0, address(this), block.timestamp + 60 ); // Donates DUST IERC20(fei).safeTransfer( IController(controller).treasury(), IERC20(fei).balanceOf(address(this)) ); IERC20(tribe).safeTransfer( IController(controller).treasury(), IERC20(tribe).balanceOf(address(this)) ); } // We want to get back FEI-TRIBE LP tokens deposit(); } } pragma solidity 0.8.2; import "./StrategyBase.sol"; // Base contract for SNX Staking rewards contract interfaces abstract contract StrategyStakingRewardsBase is StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public rewards; // **** Getters **** constructor( address _rewards, address _want, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyBase(_want, _governance, _strategist, _controller, _neuronTokenAddress, _timelock) { rewards = _rewards; } function balanceOfPool() public view override 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./StrategySushiFarmBaseCustomHarvest.sol"; contract StrategySushiEthSushiLp is StrategySushiFarmBaseCustomHarvest { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Token/ETH pool id in MasterChef contract uint256 public constant sushi_eth_poolId = 12; // Token addresses address public constant sushi_eth_sushi_lp = 0x795065dCc9f64b5614C407a6EFDC400DA6221FB0; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiFarmBaseCustomHarvest( sushi, sushi_eth_poolId, sushi_eth_sushi_lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategySushiEthSushiLp"; } // **** 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 SUSHI tokens ISushiChef(masterChef).deposit(poolId, 0); uint256 _sushi = IERC20(sushi).balanceOf(address(this)); if (_sushi > 0) { _swapToNeurAndDistributePerformanceFees(sushi, sushiRouter); } _sushi = IERC20(sushi).balanceOf(address(this)); if (_sushi > 0) { // 10% is locked up for future gov uint256 _keepSUSHI = _sushi.mul(keepSUSHI).div(keepSUSHIMax); IERC20(sushi).safeTransfer( IController(controller).treasury(), _keepSUSHI ); uint256 _swap = _sushi.sub(_keepSUSHI); IERC20(sushi).safeApprove(sushiRouter, 0); IERC20(sushi).safeApprove(sushiRouter, _swap); // swap only half of sushi cause since it's used in lp itself _swapSushiswap(sushi, weth, _swap.div(2)); } // Swap entire WETH for token1 uint256 _weth = IERC20(weth).balanceOf(address(this)); // Adds in liquidity for ETH/sushi uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_weth > 0 && _token1 > 0) { IERC20(token1).safeApprove(sushiRouter, 0); IERC20(token1).safeApprove(sushiRouter, _token1); IUniswapRouterV2(sushiRouter).addLiquidity( weth, token1, _weth, _token1, 0, 0, address(this), block.timestamp + 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)) ); } deposit(); } } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../lib/YearnAffiliateWrapper.sol"; import "../interfaces/IController.sol"; contract StrategyYearnAffiliate is YearnAffiliateWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; // User accounts address public governance; address public controller; address public strategist; address public timelock; address public want; string public name; modifier onlyGovernance() { require(msg.sender == governance); _; } // **** Getters **** constructor( address _want, address _yearnRegistry, address _governance, address _strategist, address _controller, address _timelock ) YearnAffiliateWrapper(_want, _yearnRegistry) { 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; name = string( abi.encodePacked("y", ERC20(_want).symbol(), " Affiliate Strategy") ); } function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOf() public view returns (uint256) { return totalVaultBalance(address(this)); } function balanceOfPool() public view returns (uint256) { return balanceOf(); } function getName() external view returns (string memory) { return name; } // **** Setters **** function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } function deposit() public { require(msg.sender == controller, "!controller"); uint256 _want = IERC20(want).balanceOf(address(this)); _deposit(address(this), address(this), _want, false); } // 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 pool withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); _withdrawSome(_amount); uint256 _balance = IERC20(want).balanceOf(address(this)); address _pool = IController(controller).nPools(address(want)); require(_pool != address(0), "!pool"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_pool, _balance); } // 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 _pool = IController(controller).nPools(address(want)); require(_pool != address(0), "!pool"); IERC20(want).safeTransfer(_pool, balance); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawSome(balanceOf()); balance = IERC20(want).balanceOf(address(this)); address _pool = IController(controller).nPools(address(want)); require(_pool != address(0), "!pool"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_pool, balance); } function _withdrawSome(uint256 _amount) internal returns (uint256) { return _withdraw(address(this), address(this), _amount, true); // `true` = withdraw from `bestVault` } // **** 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) } } } function migrate() external onlyGovernance returns (uint256) { return _migrate(address(this)); } function migrate(uint256 amount) external onlyGovernance returns (uint256) { return _migrate(address(this), amount); } function migrate(uint256 amount, uint256 maxMigrationLoss) external onlyGovernance returns (uint256) { return _migrate(address(this), amount, maxMigrationLoss); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.2; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; interface RegistryAPI { function governance() external view returns (address); function latestVault(address token) external view returns (address); function numVaults(address token) external view returns (uint256); function vaults(address token, uint256 deploymentId) external view returns (address); } interface VaultAPI is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256); 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); // 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 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); } abstract contract YearnAffiliateWrapper { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public token; // Reduce number of external calls (SLOADs stay the same) VaultAPI[] private _cachedVaults; RegistryAPI public registry; // ERC20 Unlimited Approvals (short-circuits VaultAPI.transferFrom) uint256 constant UNLIMITED_APPROVAL = type(uint256).max; // Sentinal values used to save gas on deposit/withdraw/migrate // NOTE: DEPOSIT_EVERYTHING == WITHDRAW_EVERYTHING == MIGRATE_EVERYTHING uint256 constant DEPOSIT_EVERYTHING = type(uint256).max; uint256 constant WITHDRAW_EVERYTHING = type(uint256).max; uint256 constant MIGRATE_EVERYTHING = type(uint256).max; // VaultsAPI.depositLimit is unlimited uint256 constant UNCAPPED_DEPOSITS = type(uint256).max; constructor(address _token, address _registry) { // Recommended to use a token with a `Registry.latestVault(_token) != address(0)` token = IERC20(_token); // Recommended to use `v2.registry.ychad.eth` registry = RegistryAPI(_registry); } /** * @notice * Used to update the yearn registry. * @param _registry The new _registry address. */ function setRegistry(address _registry) external { require(msg.sender == registry.governance()); // In case you want to override the registry instead of re-deploying registry = RegistryAPI(_registry); // Make sure there's no change in governance // NOTE: Also avoid bricking the wrapper from setting a bad registry require(msg.sender == registry.governance()); } /** * @notice * Used to get the most revent vault for the token using the registry. * @return An instance of a VaultAPI */ function bestVault() public virtual view returns (VaultAPI) { return VaultAPI(registry.latestVault(address(token))); } /** * @notice * Used to get all vaults from the registery for the token * @return An array containing instances of VaultAPI */ function allVaults() public virtual view returns (VaultAPI[] memory) { uint256 cache_length = _cachedVaults.length; uint256 num_vaults = registry.numVaults(address(token)); // Use cached if (cache_length == num_vaults) { return _cachedVaults; } VaultAPI[] memory vaults = new VaultAPI[](num_vaults); for (uint256 vault_id = 0; vault_id < cache_length; vault_id++) { vaults[vault_id] = _cachedVaults[vault_id]; } for (uint256 vault_id = cache_length; vault_id < num_vaults; vault_id++) { vaults[vault_id] = VaultAPI(registry.vaults(address(token), vault_id)); } return vaults; } function _updateVaultCache(VaultAPI[] memory vaults) internal { // NOTE: even though `registry` is update-able by Yearn, the intended behavior // is that any future upgrades to the registry will replay the version // history so that this cached value does not get out of date. if (vaults.length > _cachedVaults.length) { _cachedVaults = vaults; } } /** * @notice * Used to get the balance of an account accross all the vaults for a token. * @dev will be used to get the wrapper balance using totalVaultBalance(address(this)). * @param account The address of the account. * @return balance of token for the account accross all the vaults. */ function totalVaultBalance(address account) public view returns (uint256 balance) { VaultAPI[] memory vaults = allVaults(); for (uint256 id = 0; id < vaults.length; id++) { balance = balance.add(vaults[id].balanceOf(account).mul(vaults[id].pricePerShare()).div(10**uint256(vaults[id].decimals()))); } } /** * @notice * Used to get the TVL on the underlying vaults. * @return assets the sum of all the assets managed by the underlying vaults. */ function totalAssets() public view returns (uint256 assets) { VaultAPI[] memory vaults = allVaults(); for (uint256 id = 0; id < vaults.length; id++) { assets = assets.add(vaults[id].totalAssets()); } } function _deposit( address depositor, address receiver, uint256 amount, // if `MAX_UINT256`, just deposit everything bool pullFunds // If true, funds need to be pulled from `depositor` via `transferFrom` ) internal returns (uint256 deposited) { VaultAPI _bestVault = bestVault(); if (pullFunds) { if (amount != DEPOSIT_EVERYTHING) { token.safeTransferFrom(depositor, address(this), amount); } else { token.safeTransferFrom(depositor, address(this), token.balanceOf(depositor)); } } if (token.allowance(address(this), address(_bestVault)) < amount) { token.safeApprove(address(_bestVault), 0); // Avoid issues with some tokens requiring 0 token.safeApprove(address(_bestVault), UNLIMITED_APPROVAL); // Vaults are trusted } // Depositing returns number of shares deposited // NOTE: Shortcut here is assuming the number of tokens deposited is equal to the // number of shares credited, which helps avoid an occasional multiplication // overflow if trying to adjust the number of shares by the share price. uint256 beforeBal = token.balanceOf(address(this)); if (receiver != address(this)) { _bestVault.deposit(amount, receiver); } else if (amount != DEPOSIT_EVERYTHING) { _bestVault.deposit(amount); } else { _bestVault.deposit(); } uint256 afterBal = token.balanceOf(address(this)); deposited = beforeBal.sub(afterBal); // `receiver` now has shares of `_bestVault` as balance, converted to `token` here // Issue a refund if not everything was deposited if (depositor != address(this) && afterBal > 0) token.safeTransfer(depositor, afterBal); } function _withdraw( address sender, address receiver, uint256 amount, // if `MAX_UINT256`, just withdraw everything bool withdrawFromBest // If true, also withdraw from `_bestVault` ) internal returns (uint256 withdrawn) { VaultAPI _bestVault = bestVault(); VaultAPI[] memory vaults = allVaults(); _updateVaultCache(vaults); // NOTE: This loop will attempt to withdraw from each Vault in `allVaults` that `sender` // is deposited in, up to `amount` tokens. The withdraw action can be expensive, // so it if there is a denial of service issue in withdrawing, the downstream usage // of this wrapper contract must give an alternative method of withdrawing using // this function so that `amount` is less than the full amount requested to withdraw // (e.g. "piece-wise withdrawals"), leading to less loop iterations such that the // DoS issue is mitigated (at a tradeoff of requiring more txns from the end user). for (uint256 id = 0; id < vaults.length; id++) { if (!withdrawFromBest && vaults[id] == _bestVault) { continue; // Don't withdraw from the best } // Start with the total shares that `sender` has uint256 availableShares = vaults[id].balanceOf(sender); // Restrict by the allowance that `sender` has to this contract // NOTE: No need for allowance check if `sender` is this contract if (sender != address(this)) { availableShares = Math.min(availableShares, vaults[id].allowance(sender, address(this))); } // Limit by maximum withdrawal size from each vault availableShares = Math.min(availableShares, vaults[id].maxAvailableShares()); if (availableShares > 0) { // Intermediate step to move shares to this contract before withdrawing // NOTE: No need for share transfer if this contract is `sender` if (sender != address(this)) vaults[id].transferFrom(sender, address(this), availableShares); if (amount != WITHDRAW_EVERYTHING) { // Compute amount to withdraw fully to satisfy the request uint256 estimatedShares = amount .sub(withdrawn) // NOTE: Changes every iteration .mul(10**uint256(vaults[id].decimals())) .div(vaults[id].pricePerShare()); // NOTE: Every Vault is different // Limit amount to withdraw to the maximum made available to this contract // NOTE: Avoid corner case where `estimatedShares` isn't precise enough // NOTE: If `0 < estimatedShares < 1` but `availableShares > 1`, this will withdraw more than necessary if (estimatedShares > 0 && estimatedShares < availableShares) { withdrawn = withdrawn.add(vaults[id].withdraw(estimatedShares)); } else { withdrawn = withdrawn.add(vaults[id].withdraw(availableShares)); } } else { withdrawn = withdrawn.add(vaults[id].withdraw()); } // Check if we have fully satisfied the request // NOTE: use `amount = WITHDRAW_EVERYTHING` for withdrawing everything if (amount <= withdrawn) break; // withdrawn as much as we needed } } // If we have extra, deposit back into `_bestVault` for `sender` // NOTE: Invariant is `withdrawn <= amount` if (withdrawn > amount) { // Don't forget to approve the deposit if (token.allowance(address(this), address(_bestVault)) < withdrawn.sub(amount)) { token.safeApprove(address(_bestVault), UNLIMITED_APPROVAL); // Vaults are trusted } _bestVault.deposit(withdrawn.sub(amount), sender); withdrawn = amount; } // `receiver` now has `withdrawn` tokens as balance if (receiver != address(this)) token.safeTransfer(receiver, withdrawn); } function _migrate(address account) internal returns (uint256) { return _migrate(account, MIGRATE_EVERYTHING); } function _migrate(address account, uint256 amount) internal returns (uint256) { // NOTE: In practice, it was discovered that <50 was the maximum we've see for this variance return _migrate(account, amount, 0); } function _migrate( address account, uint256 amount, uint256 maxMigrationLoss ) internal returns (uint256 migrated) { VaultAPI _bestVault = bestVault(); // NOTE: Only override if we aren't migrating everything uint256 _depositLimit = _bestVault.depositLimit(); uint256 _totalAssets = _bestVault.totalAssets(); if (_depositLimit <= _totalAssets) return 0; // Nothing to migrate (not a failure) uint256 _amount = amount; if (_depositLimit < UNCAPPED_DEPOSITS && _amount < WITHDRAW_EVERYTHING) { // Can only deposit up to this amount uint256 _depositLeft = _depositLimit.sub(_totalAssets); if (_amount > _depositLeft) _amount = _depositLeft; } if (_amount > 0) { // NOTE: `false` = don't withdraw from `_bestVault` uint256 withdrawn = _withdraw(account, address(this), _amount, false); if (withdrawn == 0) return 0; // Nothing to migrate (not a failure) // NOTE: `false` = don't do `transferFrom` because it's already local migrated = _deposit(address(this), account, withdrawn, false); // NOTE: Due to the precision loss of certain calculations, there is a small inefficency // on how migrations are calculated, and this could lead to a DoS issue. Hence, this // value is made to be configurable to allow the user to specify how much is acceptable require(withdrawn.sub(migrated) <= maxMigrationLoss); } // else: nothing to migrate! (not a failure) } } // 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, 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); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategyYearnAffiliate.sol"; contract StrategyYearnUsdcV2 is StrategyYearnAffiliate { // Token addresses address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant yearn_registry = 0x50c1a2eA0a861A967D9d0FFE2AE4012c2E053804; constructor( address _governance, address _strategist, address _controller, address _timelock ) StrategyYearnAffiliate( usdc, yearn_registry, _governance, _strategist, _controller, _timelock ) {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategyYearnAffiliate.sol"; contract StrategyYearnCrvSteth is StrategyYearnAffiliate { // Token addresses address public constant crv_steth_lp = 0x06325440D014e39736583c165C2963BA99fAf14E; address public constant yearn_registry = 0x50c1a2eA0a861A967D9d0FFE2AE4012c2E053804; constructor( address _governance, address _strategist, address _controller, address _timelock ) StrategyYearnAffiliate( crv_steth_lp, yearn_registry, _governance, _strategist, _controller, _timelock ) {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategyYearnAffiliate.sol"; contract StrategyYearnCrvLusd is StrategyYearnAffiliate { // Token addresses address public constant crv_lusd_lp = 0xEd279fDD11cA84bEef15AF5D39BB4d4bEE23F0cA; address public constant yearn_registry = 0x50c1a2eA0a861A967D9d0FFE2AE4012c2E053804; constructor( address _governance, address _strategist, address _controller, address _timelock ) StrategyYearnAffiliate( crv_lusd_lp, yearn_registry, _governance, _strategist, _controller, _timelock ) {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategyYearnAffiliate.sol"; contract StrategyYearnCrvFrax is StrategyYearnAffiliate { // Token addresses address public constant crv_frax_lp = 0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B; address public constant yearn_registry = 0x50c1a2eA0a861A967D9d0FFE2AE4012c2E053804; constructor( address _governance, address _strategist, address _controller, address _timelock ) StrategyYearnAffiliate( crv_frax_lp, yearn_registry, _governance, _strategist, _controller, _timelock ) {} } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/INeuronPool.sol"; import "../interfaces/ICurve.sol"; import "../interfaces/IUniswapRouterV2.sol"; import "../interfaces/IController.sol"; import "./StrategyCurveBase.sol"; contract StrategyCurveRenCrv is StrategyCurveBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // https://www.curve.fi/ren // Curve stuff address public constant ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address public constant ren_gauge = 0xB1F2cdeC61db658F091671F5f199635aEF202CAC; address public constant ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyCurveBase( ren_pool, ren_gauge, ren_crv, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { IERC20(crv).approve(univ2Router2, type(uint256).max); } // **** Views **** function getMostPremium() public view override returns (address, uint256) { // Both 8 decimals 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 pure override returns (string memory) { return "StrategyCurveRenCrv"; } // **** 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) { _swapToNeurAndDistributePerformanceFees(crv, sushiRouter); } _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); } deposit(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./StrategyBase.sol"; import "../interfaces/ICurve.sol"; // Base contract for Curve based staking contract interfaces abstract contract StrategyCurveBase is StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Curve DAO // Pool's gauge => all the interactions are held through this address, ICurveGauge interface address public gauge; // Curve's contract address => depositing here address public curve; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public constant renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // How much CRV tokens to keep uint256 public keepCRV = 500; uint256 public keepCRVMax = 10000; constructor( // Curve's contract address => depositing here address _curve, address _gauge, // Token accepted by the contract address _want, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyBase( _want, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { curve = _curve; gauge = _gauge; } // **** Getters **** function balanceOfPool() public view override returns (uint256) { return ICurveGauge(gauge).balanceOf(address(this)); } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(address(this)); } function getMostPremium() public view virtual returns (address, uint256); // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function deposit() public override { // Checking our contract's wanted/accepted token balance 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/INeuronPool.sol"; import "../interfaces/ICurve.sol"; import "../interfaces/IUniswapRouterV2.sol"; import "../interfaces/IController.sol"; import "./StrategyCurveBase.sol"; contract StrategyCurve3Crv is StrategyCurveBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Curve stuff // Pool to deposit to. In this case it's 3CRV, accepting DAI + USDC + USDT address public constant three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // Pool's Gauge - interactions are mediated through ICurveGauge interface @ this address address public constant three_gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; // Curve 3Crv token contract address. // https://etherscan.io/address/0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490 // Etherscan states this contract manages 3Crv and USDC // The starting deposit is made with this token ^^^ address public constant three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyCurveBase( three_pool, three_gauge, three_crv, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { IERC20(crv).approve(univ2Router2, type(uint256).max); } // **** Views **** function getMostPremium() public view override 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 pure override returns (string memory) { return "StrategyCurve3Crv"; } // **** State Mutations **** // Function to harvest pool rewards, convert to stablecoins and reinvest to pool 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 // Creates CRV and transfers to strategy's address (?) ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { _swapToNeurAndDistributePerformanceFees(crv, sushiRouter); } _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 // Some tokens are accumulated in "treasury" and controller. The % is always subject to discussion. uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); // Converts CRV to stablecoins _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; // Transferring stablecoins back to Curve ICurveFi_3(curve).add_liquidity(liquidity, 0); } deposit(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/INeuronPool.sol"; import "../interfaces/ICurve.sol"; import "../interfaces/IUniswapRouterV2.sol"; import "../interfaces/IController.sol"; import "./PolygonStrategyCurveBase.sol"; contract PolygonStrategyCurveRenBtc is PolygonStrategyCurveBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Curve stuff // Pool to deposit to. In this case it's renBTC, accepting wBTC + renBTC // https://polygon.curve.fi/ren address public constant curve_renBTC_pool = 0xC2d95EEF97Ec6C17551d45e77B590dc1F9117C67; // Pool's Gauge - interactions are mediated through ICurveGauge interface @ this address address public constant curve_renBTC_gauge = 0xffbACcE0CC7C19d46132f1258FC16CF6871D153c; // Curve.fi amWBTC/renBTC (btcCRV) token contract address. // The starting deposit is made with this token ^^^ address public constant curve_renBTC_lp = 0xf8a57c1d3b9629b77b6726a042ca48990A84Fb49; address public constant wbtc = 0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6; address public constant renBTC = 0xDBf31dF14B66535aF65AaC99C32e9eA844e14501; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyCurveBase( curve_renBTC_pool, curve_renBTC_gauge, curve_renBTC_lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { IERC20(crv).approve(quickswapRouter, type(uint256).max); } // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategyCurveRenBtc"; } function getMostPremium() pure public override returns (address, uint256) { // Always return wbtc because there is no liquidity for renBTC tokens return (wbtc, 0); } // **** State Mutations **** // Function to harvest pool rewards, convert to stablecoins and reinvest to pool 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(); ICurveGauge(gauge).claim_rewards(address(this)); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { _swapToNeurAndDistributePerformanceFees(crv, quickswapRouter); } uint256 _wmatic = IERC20(wmatic).balanceOf(address(this)); if (_wmatic > 0) { _swapToNeurAndDistributePerformanceFees(wmatic, quickswapRouter); } _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(quickswapRouter, 0); IERC20(crv).safeApprove(quickswapRouter, _crv); _swapQuickswap(crv, to, _crv); } _wmatic = IERC20(wmatic).balanceOf(address(this)); if (_wmatic > 0) { IERC20(wmatic).safeApprove(quickswapRouter, 0); IERC20(wmatic).safeApprove(quickswapRouter, _wmatic); _swapQuickswap(wmatic, to, _wmatic); } // 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; // Transferring stablecoins back to Curve ICurveFi_Polygon_3(curve).add_liquidity(liquidity, 0, true); } deposit(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PolygonStrategyBase.sol"; import "../interfaces/ICurve.sol"; // Base contract for Curve based staking contract interfaces abstract contract PolygonStrategyCurveBase is PolygonStrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Curve DAO // Pool's gauge => all the interactions are held through this address, ICurveGauge interface address public immutable gauge; // Curve's contract address => depositing here address public immutable curve; // stablecoins address public constant dai = 0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063; address public constant usdc = 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174; address public constant usdt = 0xc2132D05D31c914a87C6611C10748AEb04B58e8F; // rewards address public constant crv = 0x172370d5Cd63279eFa6d502DAB29171933a610AF; // How much CRV tokens to keep uint256 public keepCRV = 500; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _want, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyBase( _want, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { curve = _curve; gauge = _gauge; } // **** Getters **** function balanceOfPool() public view override returns (uint256) { return ICurveGauge(gauge).balanceOf(address(this)); } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(address(this)); } function getMostPremium() public view virtual returns (address, uint256); // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function deposit() public override { // Checking our contract's wanted/accepted token balance 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; } } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/INeuronPool.sol"; import "../interfaces/IStakingRewards.sol"; import "../interfaces/IUniswapRouterV2.sol"; import "../interfaces/IController.sol"; // Strategy Contract Basics abstract contract PolygonStrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees - start with 30% uint256 public performanceTreasuryFee = 3000; uint256 public constant performanceTreasuryMax = 10000; // Withdrawal fee 0% // - 0% to treasury // - 0% to dev fund uint256 public withdrawalTreasuryFee = 0; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 0; uint256 public constant withdrawalDevFundMax = 100000; // Tokens // Input token accepted by the contract address public immutable neuronTokenAddress; address public immutable want; address public constant weth = 0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619; address public constant wmatic = 0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex - quickswap address public quickswapRouter = 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff; address public sushiRouter = 0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506; mapping(address => bool) public harvesters; constructor( // Input token accepted by the contract address _want, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_neuronTokenAddress != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; neuronTokenAddress = _neuronTokenAddress; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent() { require( harvesters[msg.sender] || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view virtual returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external pure virtual returns (string memory); // **** Setters **** // function whitelistHarvester(address _harvester) external { require( msg.sender == governance || msg.sender == strategist, "not authorized" ); harvesters[_harvester] = true; } function revokeHarvester(address _harvester) external { require( msg.sender == governance || msg.sender == strategist, "not authorized" ); harvesters[_harvester] = false; } 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 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 pool 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 _nPool = IController(controller).nPools(address(want)); require(_nPool != address(0), "!nPool"); // additional protection so we don't burn the funds IERC20(want).safeTransfer( _nPool, _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 _nPool = IController(controller).nPools(address(want)); require(_nPool != address(0), "!nPool"); IERC20(want).safeTransfer(_nPool, 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 _nPool = IController(controller).nPools(address(want)); require(_nPool != address(0), "!nPool"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_nPool, 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 _swapQuickswap( address _from, address _to, uint256 _amount ) internal { 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; } IUniswapRouterV2(quickswapRouter).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapQuickswapWithPath(address[] memory path, uint256 _amount) internal { require(path[1] != address(0)); IUniswapRouterV2(quickswapRouter).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapSushiswap( address _from, address _to, uint256 _amount ) internal { 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; } IUniswapRouterV2(sushiRouter).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapSushiswapWithPath(address[] memory path, uint256 _amount) internal { require(path[1] != address(0)); IUniswapRouterV2(sushiRouter).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ); } function _swapWithUniLikeRouter( address routerAddress, address _from, address _to, uint256 _amount ) internal returns (bool) { require(_to != address(0)); require( routerAddress != address(0), "_swapWithUniLikeRouter routerAddress cant be zero" ); 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; } try IUniswapRouterV2(routerAddress).swapExactTokensForTokens( _amount, 0, path, address(this), block.timestamp.add(60) ) { return true; } catch { return false; } } function _swapToNeurAndDistributePerformanceFees( address swapToken, address swapRouterAddress ) internal { uint256 swapTokenBalance = IERC20(swapToken).balanceOf(address(this)); if (swapTokenBalance > 0 && performanceTreasuryFee > 0) { uint256 performanceTreasuryFeeAmount = swapTokenBalance .mul(performanceTreasuryFee) .div(performanceTreasuryMax); uint256 totalFeeAmout = performanceTreasuryFeeAmount; _swapAmountToNeurAndDistributePerformanceFees( swapToken, totalFeeAmout, swapRouterAddress ); } } function _swapAmountToNeurAndDistributePerformanceFees( address swapToken, uint256 amount, address swapRouterAddress ) internal { uint256 swapTokenBalance = IERC20(swapToken).balanceOf(address(this)); require( swapTokenBalance >= amount, "Amount is bigger than token balance" ); IERC20(swapToken).safeApprove(swapRouterAddress, 0); IERC20(weth).safeApprove(swapRouterAddress, 0); IERC20(swapToken).safeApprove(swapRouterAddress, amount); IERC20(weth).safeApprove(swapRouterAddress, type(uint256).max); bool isSuccesfullSwap = _swapWithUniLikeRouter( swapRouterAddress, swapToken, neuronTokenAddress, amount ); if (isSuccesfullSwap) { uint256 neuronTokenBalance = IERC20(neuronTokenAddress).balanceOf( address(this) ); if (neuronTokenBalance > 0) { // Treasury fees // Sending strategy's tokens to treasury. Initially @ 30% (set by performanceTreasuryFee constant) of strategy's assets IERC20(neuronTokenAddress).safeTransfer( IController(controller).treasury(), neuronTokenBalance ); } } else { // If failed swap to Neuron just transfer swap token to treasury IERC20(swapToken).safeApprove( IController(controller).treasury(), 0 ); IERC20(swapToken).safeApprove( IController(controller).treasury(), amount ); IERC20(swapToken).safeTransfer( IController(controller).treasury(), amount ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./PolygonStrategyBase.sol"; import "../interfaces/IPolygonSushiMiniChef.sol"; import "../interfaces/IPolygonSushiRewarder.sol"; abstract contract PolygonStrategySushiDoubleRewardBase is PolygonStrategyBase { using SafeERC20 for IERC20; using SafeMath for uint256; // Token addresses address public constant sushi = 0x0b3F868E0BE5597D5DB7fEB59E1CADBb0fdDa50a; address public constant rewardToken = wmatic; address public constant sushiMiniChef = 0x0769fd68dFb93167989C6f7254cd0D766Fb2841F; uint256 public immutable poolId; address public immutable token0; address public immutable token1; // How much Reward tokens to keep uint256 public keepRewardToken = 500; uint256 public keepRewardTokenMax = 10000; constructor( address _token0, address _token1, uint256 _poolId, address _lp, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyBase( _lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { poolId = _poolId; token0 = _token0; token1 = _token1; } function setKeepRewardToken(uint256 _keepRewardToken) external { require(msg.sender == governance, "!governance"); keepRewardToken = _keepRewardToken; } function balanceOfPool() public view override returns (uint256) { (uint256 amount, ) = IPolygonSushiMiniChef(sushiMiniChef).userInfo( poolId, address(this) ); return amount; } function getHarvestable() external view returns (uint256, uint256) { uint256 _pendingSushi = IPolygonSushiMiniChef(sushiMiniChef) .pendingSushi(poolId, address(this)); IPolygonSushiRewarder rewarder = IPolygonSushiRewarder( IPolygonSushiMiniChef(sushiMiniChef).rewarder(poolId) ); (, uint256[] memory _rewardAmounts) = rewarder.pendingTokens( poolId, address(this), 0 ); uint256 _pendingRewardToken; if (_rewardAmounts.length > 0) { _pendingRewardToken = _rewardAmounts[0]; } return (_pendingSushi, _pendingRewardToken); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(sushiMiniChef, 0); IERC20(want).safeApprove(sushiMiniChef, _want); IPolygonSushiMiniChef(sushiMiniChef).deposit( poolId, _want, address(this) ); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IPolygonSushiMiniChef(sushiMiniChef).withdraw( poolId, _amount, address(this) ); return _amount; } // **** 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 Sushi and Reward tokens IPolygonSushiMiniChef(sushiMiniChef).harvest(poolId, address(this)); uint256 _rewardToken = IERC20(rewardToken).balanceOf(address(this)); uint256 _sushi = IERC20(sushi).balanceOf(address(this)); if (_rewardToken > 0) { _swapToNeurAndDistributePerformanceFees(rewardToken, sushiRouter); uint256 _keepRewardToken = _rewardToken.mul(keepRewardToken).div( keepRewardTokenMax ); if (_keepRewardToken > 0) { IERC20(rewardToken).safeTransfer( IController(controller).treasury(), _keepRewardToken ); } _rewardToken = IERC20(rewardToken).balanceOf(address(this)); } if (_sushi > 0) { _swapToNeurAndDistributePerformanceFees(sushi, sushiRouter); _sushi = IERC20(sushi).balanceOf(address(this)); } if (_rewardToken > 0) { IERC20(rewardToken).safeApprove(sushiRouter, 0); IERC20(rewardToken).safeApprove(sushiRouter, _rewardToken); _swapSushiswap(rewardToken, weth, _rewardToken); } if (_sushi > 0) { IERC20(sushi).safeApprove(sushiRouter, 0); IERC20(sushi).safeApprove(sushiRouter, _sushi); _swapSushiswap(sushi, weth, _sushi); } // Swap half WETH for token0 uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0 && token0 != weth) { _swapSushiswap(weth, token0, _weth.div(2)); } // Swap half WETH for token1 if (_weth > 0 && token1 != weth) { _swapSushiswap(weth, token1, _weth.div(2)); } uint256 _token0 = IERC20(token0).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_token0 > 0 && _token1 > 0) { IERC20(token0).safeApprove(sushiRouter, 0); IERC20(token0).safeApprove(sushiRouter, _token0); IERC20(token1).safeApprove(sushiRouter, 0); IERC20(token1).safeApprove(sushiRouter, _token1); IUniswapRouterV2(sushiRouter).addLiquidity( token0, token1, _token0, _token1, 0, 0, address(this), block.timestamp + 60 ); // Donates DUST IERC20(token0).transfer( IController(controller).treasury(), IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeTransfer( IController(controller).treasury(), IERC20(token1).balanceOf(address(this)) ); } deposit(); } } pragma solidity 0.8.2; pragma experimental ABIEncoderV2; interface IPolygonSushiMiniChef { event Deposit( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition( uint256 indexed pid, uint256 allocPoint, address indexed lpToken, address indexed rewarder ); event LogSetPool( uint256 indexed pid, uint256 allocPoint, address indexed rewarder, bool overwrite ); event LogSushiPerSecond(uint256 sushiPerSecond); event LogUpdatePool( uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accSushiPerShare ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event Withdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); function SUSHI() external view returns (address); function add( uint256 allocPoint, address _lpToken, address _rewarder ) external; function batch(bytes[] memory calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results); function claimOwnership() external; function deposit( uint256 pid, uint256 amount, address to ) external; function emergencyWithdraw(uint256 pid, address to) external; function harvest(uint256 pid, address to) external; function lpToken(uint256) external view returns (address); function massUpdatePools(uint256[] memory pids) external; function migrate(uint256 _pid) external; function migrator() external view returns (address); function owner() external view returns (address); function pendingOwner() external view returns (address); function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending); function permitToken( address token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function poolInfo(uint256) external view returns ( uint128 accSushiPerShare, uint64 lastRewardTime, uint64 allocPoint ); function poolLength() external view returns (uint256 pools); function rewarder(uint256) external view returns (address); function set( uint256 _pid, uint256 _allocPoint, address _rewarder, bool overwrite ) external; function setMigrator(address _migrator) external; function setSushiPerSecond(uint256 _sushiPerSecond) external; function sushiPerSecond() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function transferOwnership( address newOwner, bool direct, bool renounce ) external; function updatePool(uint256 pid) external returns (MiniChefV2.PoolInfo memory pool); function userInfo(uint256, address) external view returns (uint256 amount, int256 rewardDebt); function withdraw( uint256 pid, uint256 amount, address to ) external; function withdrawAndHarvest( uint256 pid, uint256 amount, address to ) external; } interface MiniChefV2 { struct PoolInfo { uint128 accSushiPerShare; uint64 lastRewardTime; uint64 allocPoint; } } pragma solidity 0.8.2; pragma experimental ABIEncoderV2; interface IPolygonSushiRewarder { event LogInit(); event LogOnReward( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint); event LogRewardPerSecond(uint256 rewardPerSecond); event LogSetPool(uint256 indexed pid, uint256 allocPoint); event LogUpdatePool( uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accSushiPerShare ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function add(uint256 allocPoint, uint256 _pid) external; function claimOwnership() external; function massUpdatePools(uint256[] memory pids) external; function onSushiReward( uint256 pid, address _user, address to, uint256, uint256 lpToken ) external; function owner() external view returns (address); function pendingOwner() external view returns (address); function pendingToken(uint256 _pid, address _user) external view returns (uint256 pending); function pendingTokens( uint256 pid, address user, uint256 ) external view returns (address[] memory rewardTokens, uint256[] memory rewardAmounts); function poolIds(uint256) external view returns (uint256); function poolInfo(uint256) external view returns ( uint128 accSushiPerShare, uint64 lastRewardTime, uint64 allocPoint ); function poolLength() external view returns (uint256 pools); function rewardPerSecond() external view returns (uint256); function set(uint256 _pid, uint256 _allocPoint) external; function setRewardPerSecond(uint256 _rewardPerSecond) external; function transferOwnership( address newOwner, bool direct, bool renounce ) external; function updatePool(uint256 pid) external returns (ComplexRewarderTime.PoolInfo memory pool); function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); } interface ComplexRewarderTime { struct PoolInfo { uint128 accSushiPerShare; uint64 lastRewardTime; uint64 allocPoint; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./PolygonStrategyBase.sol"; import "../interfaces/IPolygonSushiMiniChef.sol"; import "../interfaces/IPolygonSushiRewarder.sol"; import "./PolygonStrategyStakingRewardsBase.sol"; abstract contract PolygonStrategyQuickswapBase is PolygonStrategyStakingRewardsBase { using SafeERC20 for IERC20; using SafeMath for uint256; // Token addresses address public constant quick = 0x831753DD7087CaC61aB5644b308642cc1c33Dc13; address public constant rewardToken = quick; address public token0; address public token1; // How much Reward tokens to keep uint256 public keepRewardToken = 0; uint256 public keepRewardTokenMax = 10000; constructor( address _token0, address _token1, address _staking_rewards, address _lp_token, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyStakingRewardsBase( _staking_rewards, _lp_token, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { token0 = _token0; token1 = _token1; IERC20(token0).approve(quickswapRouter, type(uint256).max); IERC20(token1).approve(quickswapRouter, type(uint256).max); } function setKeepRewardToken(uint256 _keepRewardToken) external { require(msg.sender == governance, "!governance"); keepRewardToken = _keepRewardToken; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Collects Quick tokens IStakingRewards(rewards).getReward(); uint256 _rewardToken = IERC20(rewardToken).balanceOf(address(this)); if (_rewardToken > 0 && performanceTreasuryFee > 0) { _swapToNeurAndDistributePerformanceFees(rewardToken, quickswapRouter); uint256 _keepRewardToken = _rewardToken.mul(keepRewardToken).div( keepRewardTokenMax ); if (_keepRewardToken > 0) { IERC20(rewardToken).safeTransfer( IController(controller).treasury(), _keepRewardToken ); } _rewardToken = IERC20(rewardToken).balanceOf(address(this)); } if (_rewardToken > 0) { IERC20(rewardToken).safeApprove(sushiRouter, 0); IERC20(rewardToken).safeApprove(sushiRouter, _rewardToken); _swapQuickswap(rewardToken, weth, _rewardToken); } // Swap half WETH for token0 uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0 && token0 != weth) { _swapQuickswap(weth, token0, _weth.div(2)); } // Swap half WETH for token1 if (_weth > 0 && token1 != weth) { _swapQuickswap(weth, token1, _weth.div(2)); } uint256 _token0 = IERC20(token0).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_token0 > 0 && _token1 > 0) { IERC20(token0).safeApprove(quickswapRouter, 0); IERC20(token0).safeApprove(quickswapRouter, _token0); IERC20(token1).safeApprove(quickswapRouter, 0); IERC20(token1).safeApprove(quickswapRouter, _token1); IUniswapRouterV2(quickswapRouter).addLiquidity( token0, token1, _token0, _token1, 0, 0, address(this), block.timestamp + 60 ); // Donates DUST IERC20(token0).transfer( IController(controller).treasury(), IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeTransfer( IController(controller).treasury(), IERC20(token1).balanceOf(address(this)) ); } deposit(); } } pragma solidity 0.8.2; import "./PolygonStrategyBase.sol"; abstract contract PolygonStrategyStakingRewardsBase is PolygonStrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public rewards; // **** Getters **** constructor( address _rewards, address _want, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyBase( _want, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { rewards = _rewards; } function balanceOfPool() public view override 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; } } pragma solidity 0.8.2; import {PolygonStrategyQuickswapBase} from "./PolygonStrategyQuickswapBase.sol"; contract PolygonStrategyQuickswapWmaticEthLp is PolygonStrategyQuickswapBase { address public constant wmaticEthLpToken = 0xadbF1854e5883eB8aa7BAf50705338739e558E5b; address public constant wmaticEthRewards = 0x8FF56b5325446aAe6EfBf006a4C1D88e4935a914; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyQuickswapBase( wmatic, weth, wmaticEthRewards, wmaticEthLpToken, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategyQuickswapWmaticEthLp"; } } pragma solidity 0.8.2; import {PolygonStrategyQuickswapBase} from "./PolygonStrategyQuickswapBase.sol"; contract PolygonStrategyQuickswapWbtcEthLp is PolygonStrategyQuickswapBase { // token0 address public constant wbtc = 0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6; address public constant wbtcWethLpToken = 0xdC9232E2Df177d7a12FdFf6EcBAb114E2231198D; address public constant wbtcWethRewards = 0x070D182EB7E9C3972664C959CE58C5fC6219A7ad; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyQuickswapBase( wbtc, weth, wbtcWethRewards, wbtcWethLpToken, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategyQuickswapWbtcEthLp"; } } pragma solidity 0.8.2; import {PolygonStrategyQuickswapBase} from "./PolygonStrategyQuickswapBase.sol"; contract PolygonStrategyQuickswapUsdcUsdtLp is PolygonStrategyQuickswapBase { // token0 address public constant usdc = 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174; // token1 address public constant usdt = 0xc2132D05D31c914a87C6611C10748AEb04B58e8F; address public constant usdcUsdtLpToken = 0x2cF7252e74036d1Da831d11089D326296e64a728; address public constant usdcUsdtRewards = 0x251d9837a13F38F3Fe629ce2304fa00710176222; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyQuickswapBase( usdc, usdt, usdcUsdtRewards, usdcUsdtLpToken, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategyQuickswapUsdcUsdtLp"; } } pragma solidity 0.8.2; import {PolygonStrategyQuickswapBase} from "./PolygonStrategyQuickswapBase.sol"; contract PolygonStrategyQuickswapMimaticUsdcLp is PolygonStrategyQuickswapBase { // token0 address public constant usdc = 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174; // token1 address public constant miMatic = 0xa3Fa99A148fA48D14Ed51d610c367C61876997F1; address public constant miMaticUsdcLpToken = 0x160532D2536175d65C03B97b0630A9802c274daD; address public constant miMaticUsdcRewards = 0x1fdDd7F3A4c1f0e7494aa8B637B8003a64fdE21A; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyQuickswapBase( usdc, miMatic, miMaticUsdcRewards, miMaticUsdcLpToken, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategyQuickswapMimaticUsdcLp"; } } pragma solidity 0.8.2; import {PolygonStrategyQuickswapBase} from "./PolygonStrategyQuickswapBase.sol"; contract PolygonStrategyQuickswapDaiUsdtLp is PolygonStrategyQuickswapBase { // token0 address public constant dai = 0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063; // token1 address public constant usdt = 0xc2132D05D31c914a87C6611C10748AEb04B58e8F; address public constant daiUsdtLpToken = 0x59153f27eeFE07E5eCE4f9304EBBa1DA6F53CA88; address public constant daiUsdtRewards = 0x97Efe8470727FeE250D7158e6f8F63bb4327c8A2; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyQuickswapBase( usdt, dai, daiUsdtRewards, daiUsdtLpToken, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategyQuickswapDaiUsdtLp"; } } pragma solidity 0.8.2; import {PolygonStrategyQuickswapBase} from "./PolygonStrategyQuickswapBase.sol"; contract PolygonStrategyQuickswapDaiUsdcLp is PolygonStrategyQuickswapBase { // token0 address public constant dai =0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063; // token1 address public constant usdc = 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174; address public constant daiUsdcLpToken = 0xf04adBF75cDFc5eD26eeA4bbbb991DB002036Bdd; address public constant daiUsdcRewards = 0xEd8413eCEC87c3d4664975743c02DB3b574012a7; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyQuickswapBase( usdc, dai, daiUsdcRewards, daiUsdcLpToken, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategyQuickswapDaiUsdcLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./StrategyBase.sol"; import "../interfaces/ISushiMasterchefV2.sol"; import "../interfaces/ISushiRewarder.sol"; abstract contract StrategySushiEthFarmDoubleRewardBase is StrategyBase { using SafeERC20 for IERC20; using SafeMath for uint256; // Token addresses address public constant sushi = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; address public immutable rewardToken; address public constant sushiMasterChef = 0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d; uint256 public poolId; // How much Reward tokens to keep uint256 public keepRewardToken = 500; uint256 public keepRewardTokenMax = 10000; constructor( uint256 _poolId, address _lp, address _rewardToken, address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategyBase( _lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { poolId = _poolId; rewardToken = _rewardToken; } function setKeepRewardToken(uint256 _keepRewardToken) external { require(msg.sender == governance, "!governance"); keepRewardToken = _keepRewardToken; } function balanceOfPool() public view override returns (uint256) { (uint256 amount, ) = ISushiMasterchefV2(sushiMasterChef).userInfo( poolId, address(this) ); return amount; } function getHarvestableSushi() public view returns (uint256) { return ISushiMasterchefV2(sushiMasterChef).pendingSushi( poolId, address(this) ); } function getHarvestableRewardToken() public view returns (uint256) { address rewarder = ISushiMasterchefV2(sushiMasterChef).rewarder(poolId); return ISushiRewarder(rewarder).pendingToken(poolId, address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(sushiMasterChef, 0); IERC20(want).safeApprove(sushiMasterChef, _want); ISushiMasterchefV2(sushiMasterChef).deposit( poolId, _want, address(this) ); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ISushiMasterchefV2(sushiMasterChef).withdraw( poolId, _amount, address(this) ); return _amount; } // **** 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 Sushi and Reward tokens ISushiMasterchefV2(sushiMasterChef).harvest(poolId, address(this)); uint256 _rewardToken = IERC20(rewardToken).balanceOf(address(this)); uint256 _sushi = IERC20(sushi).balanceOf(address(this)); if (_rewardToken > 0) { _swapToNeurAndDistributePerformanceFees(rewardToken, sushiRouter); uint256 _keepRewardToken = _rewardToken.mul(keepRewardToken).div( keepRewardTokenMax ); if (_keepRewardToken > 0) { IERC20(rewardToken).safeTransfer( IController(controller).treasury(), _keepRewardToken ); } _rewardToken = IERC20(rewardToken).balanceOf(address(this)); } if (_sushi > 0) { _swapToNeurAndDistributePerformanceFees(sushi, sushiRouter); _sushi = IERC20(sushi).balanceOf(address(this)); } if (_rewardToken > 0) { uint256 _amount = _rewardToken.div(2); IERC20(rewardToken).safeApprove(sushiRouter, 0); IERC20(rewardToken).safeApprove(sushiRouter, _amount); _swapSushiswap(rewardToken, weth, _amount); } if (_sushi > 0) { uint256 _amount = _sushi.div(2); IERC20(sushi).safeApprove(sushiRouter, 0); IERC20(sushi).safeApprove(sushiRouter, _sushi); _swapSushiswap(sushi, weth, _amount); _swapSushiswap(sushi, rewardToken, _amount); } // Adds in liquidity for WETH/rewardToken uint256 _weth = IERC20(weth).balanceOf(address(this)); _rewardToken = IERC20(rewardToken).balanceOf(address(this)); if (_weth > 0 && _rewardToken > 0) { IERC20(weth).safeApprove(sushiRouter, 0); IERC20(weth).safeApprove(sushiRouter, _weth); IERC20(rewardToken).safeApprove(sushiRouter, 0); IERC20(rewardToken).safeApprove(sushiRouter, _rewardToken); IUniswapRouterV2(sushiRouter).addLiquidity( weth, rewardToken, _weth, _rewardToken, 0, 0, address(this), block.timestamp + 60 ); // Donates DUST IERC20(weth).transfer( IController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(rewardToken).safeTransfer( IController(controller).treasury(), IERC20(rewardToken).balanceOf(address(this)) ); } deposit(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; // interface for Sushiswap MasterChef contract interface ISushiMasterchefV2 { function MASTER_PID() external view returns (uint256); function MASTER_CHEF() external view returns (address); function rewarder(uint256 pid) external view returns (address); function add( uint256 _allocPoint, address _lpToken, address _rewarder ) external; function deposit( uint256 _pid, uint256 _amount, address _to ) external; function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function sushiPerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( uint256 lastRewardBlock, uint256 accsushiPerShare, uint256 allocPoint ); function poolLength() external view returns (uint256); function set( uint256 _pid, uint256 _allocPoint, address _rewarder, bool overwrite ) external; function harvestFromMasterChef() external; function harvest(uint256 pid, address to) external; function totalAllocPoint() external view returns (uint256); function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw( uint256 _pid, uint256 _amount, address _to ) external; function withdrawAndHarvest( uint256 _pid, uint256 _amount, address _to ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; // interface for Sushiswap MasterChef contract interface ISushiRewarder { function pendingToken(uint256 pid, address user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategySushiEthFarmDoubleRewardBase.sol"; contract StrategySushiDoubleEthRulerLp is StrategySushiEthFarmDoubleRewardBase { uint256 public constant sushi_ruler_poolId = 7; address public constant sushi_eth_ruler_lp = 0xb1EECFea192907fC4bF9c4CE99aC07186075FC51; address public constant ruler = 0x2aECCB42482cc64E087b6D2e5Da39f5A7A7001f8; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiEthFarmDoubleRewardBase( sushi_ruler_poolId, sushi_eth_ruler_lp, ruler, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategySushiDoubleEthRulerLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategySushiEthFarmDoubleRewardBase.sol"; contract StrategySushiDoubleEthPickleLp is StrategySushiEthFarmDoubleRewardBase { uint256 public constant sushi_pickle_poolId = 3; address public constant sushi_eth_pickle_lp = 0x269Db91Fc3c7fCC275C2E6f22e5552504512811c; address public constant pickle = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiEthFarmDoubleRewardBase( sushi_pickle_poolId, sushi_eth_pickle_lp, pickle, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategySushiDoubleEthPickleLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategySushiEthFarmDoubleRewardBase.sol"; contract StrategySushiDoubleEthCvxLp is StrategySushiEthFarmDoubleRewardBase { uint256 public constant sushi_cvx_poolId = 1; address public constant sushi_eth_cvx_lp = 0x05767d9EF41dC40689678fFca0608878fb3dE906; address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiEthFarmDoubleRewardBase( sushi_cvx_poolId, sushi_eth_cvx_lp, cvx, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategySushiDoubleEthCvxLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategySushiEthFarmDoubleRewardBase.sol"; contract StrategySushiDoubleEthAlcxLp is StrategySushiEthFarmDoubleRewardBase { uint256 public constant sushi_alcx_poolId = 0; address public constant sushi_eth_alcx_lp = 0xC3f279090a47e80990Fe3a9c30d24Cb117EF91a8; address public constant alcx = 0xdBdb4d16EdA451D0503b854CF79D55697F90c8DF; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiEthFarmDoubleRewardBase( sushi_alcx_poolId, sushi_eth_alcx_lp, alcx, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategySushiDoubleEthAlcxLp"; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./PolygonStrategySushiDoubleRewardBase.sol"; contract PolygonStrategySushiDoubleDaiPickleLp is PolygonStrategyBase { using SafeERC20 for IERC20; using SafeMath for uint256; // Token addresses address public constant sushi = 0x0b3F868E0BE5597D5DB7fEB59E1CADBb0fdDa50a; address public constant rewardToken = wmatic; address public constant sushiMiniChef = 0x0769fd68dFb93167989C6f7254cd0D766Fb2841F; // How much Reward tokens to keep uint256 public keepRewardToken = 500; uint256 public keepRewardTokenMax = 10000; address public constant sushi_dai_pickle_lp = 0x57602582eB5e82a197baE4E8b6B80E39abFC94EB; uint256 public constant sushi_dai_pickle_poolId = 37; // Token0 address public constant pickle_token = 0x2b88aD57897A8b496595925F43048301C37615Da; // Token1 address public constant dai = 0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063; address public constant token0 = pickle_token; address public constant token1 = dai; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyBase( sushi_dai_pickle_lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "PolygonStrategySushiDoubleDaiPickleLp"; } function setKeepRewardToken(uint256 _keepRewardToken) external { require(msg.sender == governance, "!governance"); keepRewardToken = _keepRewardToken; } function balanceOfPool() public view override returns (uint256) { (uint256 amount, ) = IPolygonSushiMiniChef(sushiMiniChef).userInfo( sushi_dai_pickle_poolId, address(this) ); return amount; } function getHarvestable() external view returns (uint256, uint256) { uint256 _pendingSushi = IPolygonSushiMiniChef(sushiMiniChef) .pendingSushi(sushi_dai_pickle_poolId, address(this)); IPolygonSushiRewarder rewarder = IPolygonSushiRewarder( IPolygonSushiMiniChef(sushiMiniChef).rewarder( sushi_dai_pickle_poolId ) ); (, uint256[] memory _rewardAmounts) = rewarder.pendingTokens( sushi_dai_pickle_poolId, address(this), 0 ); uint256 _pendingRewardToken; if (_rewardAmounts.length > 0) { _pendingRewardToken = _rewardAmounts[0]; } return (_pendingSushi, _pendingRewardToken); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(sushiMiniChef, 0); IERC20(want).safeApprove(sushiMiniChef, _want); IPolygonSushiMiniChef(sushiMiniChef).deposit( sushi_dai_pickle_poolId, _want, address(this) ); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IPolygonSushiMiniChef(sushiMiniChef).withdraw( sushi_dai_pickle_poolId, _amount, address(this) ); return _amount; } 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 Sushi and Reward tokens IPolygonSushiMiniChef(sushiMiniChef).harvest( sushi_dai_pickle_poolId, address(this) ); uint256 _rewardToken = IERC20(rewardToken).balanceOf(address(this)); uint256 _sushi = IERC20(sushi).balanceOf(address(this)); if (_rewardToken > 0) { _swapToNeurAndDistributePerformanceFees(rewardToken, sushiRouter); uint256 _keepRewardToken = _rewardToken.mul(keepRewardToken).div( keepRewardTokenMax ); if (_keepRewardToken > 0) { IERC20(rewardToken).safeTransfer( IController(controller).treasury(), _keepRewardToken ); } _rewardToken = IERC20(rewardToken).balanceOf(address(this)); } if (_sushi > 0) { _swapToNeurAndDistributePerformanceFees(sushi, sushiRouter); _sushi = IERC20(sushi).balanceOf(address(this)); } if (_rewardToken > 0) { IERC20(rewardToken).safeApprove(sushiRouter, 0); IERC20(rewardToken).safeApprove(sushiRouter, _rewardToken); _swapSushiswap(rewardToken, weth, _rewardToken); } if (_sushi > 0) { IERC20(sushi).safeApprove(sushiRouter, 0); IERC20(sushi).safeApprove(sushiRouter, _sushi); _swapSushiswap(sushi, weth, _sushi); } // Swap all WETH for DAI first uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapSushiswap(weth, dai, _weth); } uint256 _dai = IERC20(dai).balanceOf(address(this)); // Swap half DAI for pickle if (_dai > 0) { IERC20(dai).safeApprove(sushiRouter, 0); IERC20(dai).safeApprove(sushiRouter, _dai.div(2)); _swapSushiswap(dai, pickle_token, _dai.div(2)); } uint256 _token0 = IERC20(token0).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_token0 > 0 && _token1 > 0) { IERC20(token0).safeApprove(sushiRouter, 0); IERC20(token0).safeApprove(sushiRouter, _token0); IERC20(token1).safeApprove(sushiRouter, 0); IERC20(token1).safeApprove(sushiRouter, _token1); IUniswapRouterV2(sushiRouter).addLiquidity( token0, token1, _token0, _token1, 0, 0, address(this), block.timestamp + 60 ); // Donates DUST IERC20(token0).transfer( IController(controller).treasury(), IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeTransfer( IController(controller).treasury(), IERC20(token1).balanceOf(address(this)) ); } deposit(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/INeuronPool.sol"; import "../interfaces/ICurve.sol"; import "../interfaces/IUniswapRouterV2.sol"; import "../interfaces/IController.sol"; import "./PolygonStrategyCurveBase.sol"; contract PolygonStrategyCurveAm3Crv is PolygonStrategyCurveBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Curve stuff // Pool to deposit to. In this case it's 3CRV, accepting DAI + USDC + USDT address public three_pool = 0x445FE580eF8d70FF569aB36e80c647af338db351; // Pool's Gauge - interactions are mediated through ICurveGauge interface @ this address address public three_gauge = 0x19793B454D3AfC7b454F206Ffe95aDE26cA6912c; // Curve 3Crv token contract address. // https://etherscan.io/address/0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490 // Etherscan states this contract manages 3Crv and USDC // The starting deposit is made with this token ^^^ address public three_crv = 0xE7a24EF0C5e95Ffb0f6684b813A78F2a3AD7D171; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) PolygonStrategyCurveBase( three_pool, three_gauge, three_crv, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) { IERC20(crv).approve(quickswapRouter, type(uint256).max); } // **** Views **** function getMostPremium() public view override returns (address, uint256) { uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_Polygon_3(curve).balances(0); // DAI balances[1] = ICurveFi_Polygon_3(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_Polygon_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 pure override returns (string memory) { return "PolygonStrategyCurveAm3Crv"; } // **** State Mutations **** // Function to harvest pool rewards, convert to stablecoins and reinvest to pool 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(); ICurveGauge(gauge).claim_rewards(address(this)); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { _swapToNeurAndDistributePerformanceFees(crv, quickswapRouter); } uint256 _wmatic = IERC20(wmatic).balanceOf(address(this)); if (_wmatic > 0) { _swapToNeurAndDistributePerformanceFees(wmatic, quickswapRouter); } _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(quickswapRouter, 0); IERC20(crv).safeApprove(quickswapRouter, _crv); _swapQuickswap(crv, to, _crv); } _wmatic = IERC20(wmatic).balanceOf(address(this)); if (_wmatic > 0) { IERC20(wmatic).safeApprove(quickswapRouter, 0); IERC20(wmatic).safeApprove(quickswapRouter, _wmatic); _swapQuickswap(wmatic, to, _wmatic); } // 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; // Transferring stablecoins back to Curve ICurveFi_Polygon_3(curve).add_liquidity(liquidity, 0, true); } deposit(); } } pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IController.sol"; import {GaugesDistributor} from "./GaugesDistributor.sol"; import {Gauge} from "./Gauge.sol"; contract NeuronPool is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Token accepted by the contract. E.g. 3Crv for 3poolCrv pool // Usually want/_want in strategies IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; uint8 public immutable _decimals; address public governance; address public timelock; address public controller; address public masterchef; GaugesDistributor public gaugesDistributor; constructor( // Token accepted by the contract. E.g. 3Crv for 3poolCrv pool // Usually want/_want in strategies address _token, address _governance, address _timelock, address _controller, address _masterchef, address _gaugesDistributor ) ERC20( string(abi.encodePacked("neuroned", ERC20(_token).name())), string(abi.encodePacked("neur", ERC20(_token).symbol())) ) { _decimals = ERC20(_token).decimals(); token = IERC20(_token); governance = _governance; timelock = _timelock; controller = _controller; masterchef = _masterchef; gaugesDistributor = GaugesDistributor(_gaugesDistributor); } function decimals() public view virtual override returns (uint8) { return _decimals; } // Balance = pool's balance + pool's token controller contract balance 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"); require(_min <= max, "numerator cannot be greater than denominator"); 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; } // Returns tokens available for deposit into the pool // Custom logic in here for how much the pools allows to be borrowed function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Depositing tokens into pool // Usually called manually in tests function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } // User's entry point; called on pressing Deposit in Neuron's UI function deposit(uint256 _amount) public { // Pool's + controller balances 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; // totalSupply - total supply of pToken, given in exchange for depositing to a pool, eg p3CRV for 3Crv if (totalSupply() == 0) { // Tokens user will get in exchange for deposit. First user receives tokens equal to deposit. shares = _amount; } else { // For subsequent users: (tokens_stacked * exist_pTokens) / total_tokens_stacked. total_tokesn_stacked - not considering first users shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function depositAndFarm(uint256 _amount) public { // Pool's + controller balances 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; // totalSupply - total supply of pToken, given in exchange for depositing to a pool, eg p3CRV for 3Crv if (totalSupply() == 0) { // Tokens user will get in exchange for deposit. First user receives tokens equal to deposit. shares = _amount; } else { // For subsequent users: (tokens_stacked * exist_pTokens) / total_tokens_stacked. total_tokesn_stacked - not considering first users shares = (_amount.mul(totalSupply())).div(_pool); } Gauge gauge = Gauge(gaugesDistributor.getGauge(address(this))); _mint(address(gauge), shares); gauge.depositStateUpdateByPool(msg.sender, shares); } function withdrawAll() external { withdrawFor(msg.sender, balanceOf(msg.sender), msg.sender); } function withdraw(uint256 _shares) external { withdrawFor(msg.sender, _shares, 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 withdrawFor( address holder, uint256 _shares, address burnFrom ) internal { // _shares - tokens user wants to withdraw uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(burnFrom, _shares); // Check balance uint256 b = token.balanceOf(address(this)); // If pool balance's not enough, we're withdrawing the controller's tokens 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(holder, r); } function withdrawAllRightFromFarm() external { Gauge gauge = Gauge(gaugesDistributor.getGauge(address(this))); uint256 shares = gauge.withdrawAllStateUpdateByPool(msg.sender); withdrawFor(msg.sender, shares, address(gauge)); } function getRatio() public view returns (uint256) { uint256 currentTotalSupply = totalSupply(); if (currentTotalSupply == 0) { return 0; } return balance().mul(1e18).div(currentTotalSupply); } } pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./Gauge.sol"; interface IMinter { function collect() external; } contract GaugesDistributor { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable NEURON; IERC20 public immutable AXON; address public governance; address public admin; uint256 public pid; uint256 public totalWeight; IMinter public minter; bool public isManualWeights = true; address[] internal _tokens; mapping(address => address) public gauges; // token => gauge mapping(address => uint256) public weights; // token => weight mapping(address => mapping(address => uint256)) public votes; // msg.sender => votes mapping(address => address[]) public tokenVote; // msg.sender => token mapping(address => uint256) public usedWeights; // msg.sender => total voting weight of user constructor( address _minter, address _neuronToken, address _axon, address _governance, address _admin ) { minter = IMinter(_minter); NEURON = IERC20(_neuronToken); AXON = IERC20(_axon); governance = _governance; admin = _admin; } function setMinter(address _minter) public { require( msg.sender == governance, "!admin and !governance" ); minter = IMinter(_minter); } function tokens() external view returns (address[] memory) { return _tokens; } function getGauge(address _token) external view returns (address) { return gauges[_token]; } // Reset votes to 0 function reset() external { _reset(msg.sender); } // Reset votes to 0 function _reset(address _owner) internal { address[] storage _tokenVote = tokenVote[_owner]; uint256 _tokenVoteCnt = _tokenVote.length; for (uint256 i = 0; i < _tokenVoteCnt; i++) { address _token = _tokenVote[i]; uint256 _votes = votes[_owner][_token]; if (_votes > 0) { totalWeight = totalWeight.sub(_votes); weights[_token] = weights[_token].sub(_votes); votes[_owner][_token] = 0; } } delete tokenVote[_owner]; } // Adjusts _owner's votes according to latest _owner's AXON balance function poke(address _owner) public { address[] memory _tokenVote = tokenVote[_owner]; uint256 _tokenCnt = _tokenVote.length; uint256[] memory _weights = new uint256[](_tokenCnt); uint256 _prevUsedWeight = usedWeights[_owner]; uint256 _weight = AXON.balanceOf(_owner); for (uint256 i = 0; i < _tokenCnt; i++) { uint256 _prevWeight = votes[_owner][_tokenVote[i]]; _weights[i] = _prevWeight.mul(_weight).div(_prevUsedWeight); } _vote(_owner, _tokenVote, _weights); } function _vote( address _owner, address[] memory _tokenVote, uint256[] memory _weights ) internal { _reset(_owner); uint256 _tokenCnt = _tokenVote.length; uint256 _weight = AXON.balanceOf(_owner); uint256 _totalVoteWeight = 0; uint256 _usedWeight = 0; for (uint256 i = 0; i < _tokenCnt; i++) { _totalVoteWeight = _totalVoteWeight.add(_weights[i]); } for (uint256 i = 0; i < _tokenCnt; i++) { address _token = _tokenVote[i]; address _gauge = gauges[_token]; uint256 _tokenWeight = _weights[i].mul(_weight).div( _totalVoteWeight ); if (_gauge != address(0x0)) { _usedWeight = _usedWeight.add(_tokenWeight); totalWeight = totalWeight.add(_tokenWeight); weights[_token] = weights[_token].add(_tokenWeight); tokenVote[_owner].push(_token); votes[_owner][_token] = _tokenWeight; } } usedWeights[_owner] = _usedWeight; } function setWeights( address[] memory _tokensToVote, uint256[] memory _weights ) external { require( msg.sender == admin || msg.sender == governance, "Set weights function can only be executed by admin or governance" ); require(isManualWeights, "Manual weights mode is off"); require( _tokensToVote.length == _weights.length, "Number Tokens to vote should be the same as weights number" ); uint256 _tokensCnt = _tokensToVote.length; uint256 _totalWeight = 0; for (uint256 i = 0; i < _tokensCnt; i++) { address _token = _tokensToVote[i]; address _gauge = gauges[_token]; uint256 _tokenWeight = _weights[i]; if (_gauge != address(0x0)) { _totalWeight = _totalWeight.add(_tokenWeight); weights[_token] = _tokenWeight; } } totalWeight = _totalWeight; } function setIsManualWeights(bool _isManualWeights) external { require(msg.sender == governance, "!governance"); isManualWeights = _isManualWeights; } // Vote with AXON on a gauge function vote(address[] calldata _tokenVote, uint256[] calldata _weights) external { require(_tokenVote.length == _weights.length); require(!isManualWeights, "isManualWeights should be false"); _vote(msg.sender, _tokenVote, _weights); } function addGauge(address _token) external { require(msg.sender == governance, "!governance"); require(gauges[_token] == address(0x0), "exists"); gauges[_token] = address( new Gauge(_token, address(NEURON), address(AXON)) ); _tokens.push(_token); } // Fetches Neurons function collect() internal { minter.collect(); } function length() external view returns (uint256) { return _tokens.length; } function distribute() external { require( msg.sender == admin || msg.sender == governance, "Distribute function can only be executed by admin or governance" ); collect(); uint256 _balance = NEURON.balanceOf(address(this)); if (_balance > 0 && totalWeight > 0) { for (uint256 i = 0; i < _tokens.length; i++) { address _token = _tokens[i]; address _gauge = gauges[_token]; uint256 _reward = _balance.mul(weights[_token]).div( totalWeight ); if (_reward > 0) { NEURON.safeApprove(_gauge, 0); NEURON.safeApprove(_gauge, _reward); Gauge(_gauge).notifyRewardAmount(_reward); } } } } function setAdmin(address _admin) external { require( msg.sender == admin || msg.sender == governance, "Only governance or admin can set admin" ); admin = _admin; } } pragma solidity 0.8.2; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IAxon} from "./interfaces/IAxon.sol"; contract Gauge is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable NEURON; IAxon public immutable AXON; IERC20 public immutable TOKEN; address public immutable DISTRIBUTION; uint256 public constant DURATION = 7 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; modifier onlyDistribution() { require( msg.sender == DISTRIBUTION, "Caller is not RewardsDistribution contract" ); _; } mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 public _totalSupply; uint256 public derivedSupply; mapping(address => uint256) private _balances; mapping(address => uint256) public derivedBalances; mapping(address => uint256) private _base; constructor( address _token, address _neuron, address _axon ) { NEURON = IERC20(_neuron); AXON = IAxon(_axon); TOKEN = IERC20(_token); DISTRIBUTION = msg.sender; } 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 Math.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(derivedSupply) ); } function derivedBalance(address account) public view returns (uint256) { uint256 _balance = _balances[account]; uint256 _derived = _balance.mul(40).div(100); uint256 axonMultiplier = 0; uint256 axonTotalSupply = AXON.totalSupply(); if (axonTotalSupply != 0) { axonMultiplier = AXON.balanceOf(account).div(AXON.totalSupply()); } uint256 _adjusted = (_totalSupply.mul(axonMultiplier)).mul(60).div(100); return Math.min(_derived.add(_adjusted), _balance); } function kick(address account) public { uint256 _derivedBalance = derivedBalances[account]; derivedSupply = derivedSupply.sub(_derivedBalance); _derivedBalance = derivedBalance(account); derivedBalances[account] = _derivedBalance; derivedSupply = derivedSupply.add(_derivedBalance); } function earned(address account) public view returns (uint256) { return derivedBalances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(DURATION); } function depositAll() external { _deposit(TOKEN.balanceOf(msg.sender), msg.sender, msg.sender); } function deposit(uint256 amount) external { _deposit(amount, msg.sender, msg.sender); } function depositFor(uint256 amount, address account) external { _deposit(amount, account, account); } function depositFromSenderFor(uint256 amount, address account) external { _deposit(amount, msg.sender, account); } function depositStateUpdate(address holder, uint256 amount) internal updateReward(holder) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[holder] = _balances[holder].add(amount); emit Staked(holder, amount); } function depositStateUpdateByPool(address holder, uint256 amount) external { require( msg.sender == address(TOKEN), "State update without transfer can only be called by pool" ); depositStateUpdate(holder, amount); } function _deposit( uint256 amount, address spender, address recipient ) internal nonReentrant { depositStateUpdate(recipient, amount); TOKEN.safeTransferFrom(spender, address(this), amount); } function withdrawAll() external { _withdraw(_balances[msg.sender]); } function withdraw(uint256 amount) external { _withdraw(amount); } function _withdraw(uint256 amount) internal nonReentrant { withdrawStateUpdate(msg.sender, amount); TOKEN.safeTransfer(msg.sender, amount); } function withdrawStateUpdate(address holder, uint256 amount) internal updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[holder] = _balances[holder].sub(amount); emit Withdrawn(holder, amount); } // We use this function when withdraw right from pool. No transfer because after that we burn this amount from contract. function withdrawAllStateUpdateByPool(address holder) external nonReentrant returns (uint256) { require( msg.sender == address(TOKEN), "Only corresponding pool can withdraw tokens for someone" ); uint256 amount = _balances[holder]; withdrawStateUpdate(holder, amount); return amount; } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; NEURON.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { _withdraw(_balances[msg.sender]); getReward(); } function notifyRewardAmount(uint256 reward) external onlyDistribution updateReward(address(0)) { NEURON.safeTransferFrom(DISTRIBUTION, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // 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 = NEURON.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; if (account != address(0)) { kick(account); } } 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); } // 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; } } pragma solidity 0.8.2; interface IAxon { function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOf(address addr) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupply() external view returns (uint256); } pragma solidity 0.8.2; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract GaugePolygon is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable NEURON; IERC20 public immutable TOKEN; address public immutable DISTRIBUTION; uint256 public constant DURATION = 7 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; modifier onlyDistribution() { require( msg.sender == DISTRIBUTION, "Caller is not RewardsDistribution contract" ); _; } mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 public _totalSupply; mapping(address => uint256) private _balances; mapping(address => uint256) private _base; constructor(address _token, address _neuron) { NEURON = IERC20(_neuron); TOKEN = IERC20(_token); DISTRIBUTION = msg.sender; } 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 Math.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(DURATION); } function depositAll() external { _deposit(TOKEN.balanceOf(msg.sender), msg.sender, msg.sender); } function deposit(uint256 amount) external { _deposit(amount, msg.sender, msg.sender); } function depositFor(uint256 amount, address account) external { _deposit(amount, account, account); } function depositFromSenderFor(uint256 amount, address account) external { _deposit(amount, msg.sender, account); } function depositStateUpdate(address holder, uint256 amount) internal updateReward(holder) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[holder] = _balances[holder].add(amount); emit Staked(holder, amount); } function depositStateUpdateByPool(address holder, uint256 amount) external { require( msg.sender == address(TOKEN), "State update without transfer can only be called by pool" ); depositStateUpdate(holder, amount); } function _deposit( uint256 amount, address spender, address recipient ) internal nonReentrant { depositStateUpdate(recipient, amount); TOKEN.safeTransferFrom(spender, address(this), amount); } function withdrawAll() external { _withdraw(_balances[msg.sender]); } function withdraw(uint256 amount) external { _withdraw(amount); } function _withdraw(uint256 amount) internal nonReentrant { withdrawStateUpdate(msg.sender, amount); TOKEN.safeTransfer(msg.sender, amount); } function withdrawStateUpdate(address holder, uint256 amount) internal updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[holder] = _balances[holder].sub(amount); emit Withdrawn(holder, amount); } // We use this function when withdraw right from pool. No transfer because after that we burn this amount from contract. function withdrawAllStateUpdateByPool(address holder) external nonReentrant returns (uint256) { require( msg.sender == address(TOKEN), "Only corresponding pool can withdraw tokens for someone" ); uint256 amount = _balances[holder]; withdrawStateUpdate(holder, amount); return amount; } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; NEURON.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { _withdraw(_balances[msg.sender]); getReward(); } function notifyRewardAmount(uint256 reward) external onlyDistribution updateReward(address(0)) { NEURON.safeTransferFrom(DISTRIBUTION, address(this), reward); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // 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 = NEURON.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } // BEFORE_DEPLOY gauges shouldn't be empty at the moment of first users staking. Set rewardPerTokenStored modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } 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); } pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./GaugePolygon.sol"; interface IMinter { function collect() external; } contract GaugesDistributorPolygon { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public immutable NEURON; address public governance; address public admin; uint256 public pid; uint256 public totalWeight; IMinter public minter; address[] internal _tokens; mapping(address => address) public gauges; // token => gauge mapping(address => uint256) public weights; // token => weight mapping(address => mapping(address => uint256)) public votes; // msg.sender => votes constructor( address _minter, address _neuronToken, address _governance, address _admin ) { minter = IMinter(_minter); NEURON = IERC20(_neuronToken); governance = _governance; admin = _admin; } function setMinter(address _minter) public { require(msg.sender == governance, "!admin and !governance"); minter = IMinter(_minter); } function tokens() external view returns (address[] memory) { return _tokens; } function getGauge(address _token) external view returns (address) { return gauges[_token]; } function setWeights( address[] memory _tokensToVote, uint256[] memory _weights ) external { require( msg.sender == admin || msg.sender == governance, "Set weights function can only be executed by admin or governance" ); require( _tokensToVote.length == _weights.length, "Number Tokens to vote should be the same as weights number" ); uint256 _tokensCnt = _tokensToVote.length; uint256 _totalWeight = 0; for (uint256 i = 0; i < _tokensCnt; i++) { address _token = _tokensToVote[i]; address _gauge = gauges[_token]; uint256 _tokenWeight = _weights[i]; if (_gauge != address(0x0)) { _totalWeight = _totalWeight.add(_tokenWeight); weights[_token] = _tokenWeight; } } totalWeight = _totalWeight; } function addGauge(address _token) external { require(msg.sender == governance, "!governance"); require(gauges[_token] == address(0x0), "exists"); gauges[_token] = address(new GaugePolygon(_token, address(NEURON))); _tokens.push(_token); } // Fetches Neurons function collect() internal { minter.collect(); } function length() external view returns (uint256) { return _tokens.length; } function distribute() external { require( msg.sender == admin || msg.sender == governance, "Distribute function can only be executed by admin or governance" ); collect(); uint256 _balance = NEURON.balanceOf(address(this)); if (_balance > 0 && totalWeight > 0) { for (uint256 i = 0; i < _tokens.length; i++) { address _token = _tokens[i]; address _gauge = gauges[_token]; uint256 _reward = _balance.mul(weights[_token]).div( totalWeight ); if (_reward > 0) { NEURON.safeApprove(_gauge, 0); NEURON.safeApprove(_gauge, _reward); GaugePolygon(_gauge).notifyRewardAmount(_reward); } } } } function setAdmin(address _admin) external { require( msg.sender == admin || msg.sender == governance, "Only governance or admin can set admin" ); admin = _admin; } } pragma solidity 0.8.2; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {AnyswapV5ERC20} from "./lib/AnyswapV5ERC20.sol"; contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // The NEURON TOKEN AnyswapV5ERC20 public neuronToken; // Dev fund (10%, initially) uint256 public devFundPercentage = 10; // Treasury (10%, initially) uint256 public treasuryPercentage = 10; address public governance; // Dev address. address public devaddr; address public treasuryAddress; // Block number when bonus NEURON period ends. uint256 public bonusEndBlock; // NEURON tokens created per block. uint256 public neuronTokenPerBlock; // Bonus muliplier for early nueron makers. uint256 public constant BONUS_MULTIPLIER = 10; // The block number when NEURON mining starts. uint256 public startBlock; address public distributor; uint256 public distributorLastRewardBlock; // 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 ); modifier onlyGovernance() { require( governance == _msgSender(), "Governance: caller is not the governance" ); _; } constructor( address _neuronToken, address _governance, address _devaddr, address _treasuryAddress, uint256 _neuronTokenPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) { neuronToken = AnyswapV5ERC20(_neuronToken); governance = _governance; devaddr = _devaddr; treasuryAddress = _treasuryAddress; distributorLastRewardBlock = block.number > startBlock ? block.number : startBlock; neuronTokenPerBlock = _neuronTokenPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; } // 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) ); } } function collect() external { require(msg.sender == distributor, "Only distributor can collect"); uint256 multiplier = getMultiplier( distributorLastRewardBlock, block.number ); distributorLastRewardBlock = block.number; uint256 neuronTokenReward = multiplier.mul(neuronTokenPerBlock); neuronToken.mint(devaddr, neuronTokenReward.div(100).mul(devFundPercentage)); neuronToken.mint(treasuryAddress, neuronTokenReward.div(100).mul(treasuryPercentage)); neuronToken.mint(distributor, neuronTokenReward); } // Safe neuronToken transfer function, just in case if rounding error causes pool to not have enough NEURs. function safeNeuronTokenTransfer(address _to, uint256 _amount) internal { uint256 neuronTokenBalance = neuronToken.balanceOf(address(this)); if (_amount > neuronTokenBalance) { neuronToken.transfer(_to, neuronTokenBalance); } else { neuronToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function setDevAddr(address _devaddr) external { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // **** Additional functions separate from the original masterchef contract **** function setNeuronTokenPerBlock(uint256 _neuronTokenPerBlock) external onlyGovernance { require(_neuronTokenPerBlock > 0, "!neuronTokenPerBlock-0"); neuronTokenPerBlock = _neuronTokenPerBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) external onlyGovernance { bonusEndBlock = _bonusEndBlock; } function setDevFundPercentage(uint256 _devFundPercentage) external onlyGovernance { require(_devFundPercentage > 0, "!devFundPercentage-0"); devFundPercentage = _devFundPercentage; } function setTreasuryPercentage(uint256 _treasuryPercentage) external onlyGovernance { require(_treasuryPercentage > 0, "!treasuryPercentage-0"); treasuryPercentage = _treasuryPercentage; } function setDistributor(address _distributor) external onlyGovernance { distributor = _distributor; distributorLastRewardBlock = block.number > startBlock ? block.number : startBlock; } } // SPDX-License-Identifier: MIT 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]; } // 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); } // 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)))); } // 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)); } } // 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: GPL-3.0-or-later pragma solidity 0.8.2; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); 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); function permit( address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function transferWithPermit( address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Returns the current ERC2612 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 Wrapped ERC-20 v10 (AnyswapV3ERC20) is an ERC-20 ERC-20 wrapper. You can `deposit` ERC-20 and obtain an AnyswapV3ERC20 balance which can then be operated as an ERC-20 token. You can /// `withdraw` ERC-20 from AnyswapV3ERC20, which will then burn AnyswapV3ERC20 token in your wallet. The amount of AnyswapV3ERC20 token in any wallet is always identical to the /// balance of ERC-20 deposited minus the ERC-20 withdrawn with that specific wallet. interface IAnyswapV3ERC20 is IERC20, IERC2612 { /// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token, /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. /// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677. function approveAndCall( address spender, uint256 value, bytes calldata data ) external returns (bool); /// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`), /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// A transfer to `address(0)` triggers an ERC-20 withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` AnyswapV3ERC20 token. /// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677. function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); } interface ITransferReceiver { function onTokenTransfer( address, uint256, bytes calldata ) external returns (bool); } interface IApprovalReceiver { function onTokenApproval( address, uint256, bytes calldata ) external returns (bool); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } 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 callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "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 AnyswapV5ERC20 is IAnyswapV3ERC20 { using SafeERC20 for IERC20; string public name; string public symbol; uint8 public immutable override decimals; address public immutable underlying; bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 public constant TRANSFER_TYPEHASH = keccak256( "Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 public immutable DOMAIN_SEPARATOR; /// @dev Records amount of AnyswapV3ERC20 token owned by account. mapping(address => uint256) public override balanceOf; uint256 private _totalSupply; // init flag for setting immediate vault, needed for CREATE2 support bool private _init; // flag to enable/disable swapout vs vault.burn so multiple events are triggered bool private _vaultOnly; // configurable delay for timelock functions // BEFORE_DEPLOY discuss delay. 2 days (default value) maybe too much. Now set to 0 for testing // uint256 public delay = 2 * 24 * 3600; uint256 public delay = 0; // set of minters, can be this bridge or other bridges mapping(address => bool) public isMinter; address[] public minters; // primary controller of the token contract address public vault; address public pendingMinter; uint256 public delayMinter; address public pendingVault; uint256 public delayVault; uint256 public pendingDelay; uint256 public delayDelay; modifier onlyAuth() { require(isMinter[msg.sender], "AnyswapV4ERC20: FORBIDDEN"); _; } modifier onlyVault() { require(msg.sender == mpc(), "AnyswapV3ERC20: FORBIDDEN"); _; } function owner() public view returns (address) { return mpc(); } function mpc() public view returns (address) { if (block.timestamp >= delayVault) { return pendingVault; } return vault; } function setVaultOnly(bool enabled) external onlyVault { _vaultOnly = enabled; } function initVault(address _vault) external onlyVault { require(_init); vault = _vault; pendingVault = _vault; isMinter[_vault] = true; minters.push(_vault); delayVault = block.timestamp; _init = false; } function setMinter(address _auth) external onlyVault { pendingMinter = _auth; delayMinter = block.timestamp + delay; } function setVault(address _vault) external onlyVault { pendingVault = _vault; delayVault = block.timestamp + delay; } function applyVault() external onlyVault { require(block.timestamp >= delayVault); vault = pendingVault; } function applyMinter() external onlyVault { require(block.timestamp >= delayMinter); isMinter[pendingMinter] = true; minters.push(pendingMinter); } // No time delay revoke minter emergency function function revokeMinter(address _auth) external onlyVault { isMinter[_auth] = false; } function getAllMinters() external view returns (address[] memory) { return minters; } function changeVault(address newVault) external onlyVault returns (bool) { require(newVault != address(0), "AnyswapV3ERC20: address(0x0)"); pendingVault = newVault; delayVault = block.timestamp + delay; emit LogChangeVault(vault, pendingVault, delayVault); return true; } function changeMPCOwner(address newVault) public onlyVault returns (bool) { require(newVault != address(0), "AnyswapV3ERC20: address(0x0)"); pendingVault = newVault; delayVault = block.timestamp + delay; emit LogChangeMPCOwner(vault, pendingVault, delayVault); return true; } function mint(address to, uint256 amount) external onlyAuth returns (bool) { _mint(to, amount); return true; } function burn(address from, uint256 amount) external onlyAuth returns (bool) { require(from != address(0), "AnyswapV3ERC20: address(0x0)"); _burn(from, amount); return true; } function Swapin( bytes32 txhash, address account, uint256 amount ) public onlyAuth returns (bool) { _mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public returns (bool) { require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth"); require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)"); _burn(msg.sender, amount); emit LogSwapout(msg.sender, bindaddr, amount); return true; } /// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}. /// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times. mapping(address => uint256) public override nonces; /// @dev Records number of AnyswapV3ERC20 token that account (second) will be allowed to spend on behalf of another account (first) through {transferFrom}. mapping(address => mapping(address => uint256)) public override allowance; event LogChangeVault( address indexed oldVault, address indexed newVault, uint256 indexed effectiveTime ); event LogChangeMPCOwner( address indexed oldOwner, address indexed newOwner, uint256 indexed effectiveHeight ); event LogSwapin( bytes32 indexed txhash, address indexed account, uint256 amount ); event LogSwapout( address indexed account, address indexed bindaddr, uint256 amount ); event LogAddAuth(address indexed auth, uint256 timestamp); constructor( string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault ) { name = _name; symbol = _symbol; decimals = _decimals; underlying = _underlying; if (_underlying != address(0x0)) { require(_decimals == IERC20(_underlying).decimals()); } // Use init to allow for CREATE2 accross all chains _init = true; // Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens _vaultOnly = false; vault = _vault; pendingVault = _vault; delayVault = block.timestamp; uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } /// @dev Returns the total supply of AnyswapV3ERC20 token as the ETH held in this contract. function totalSupply() external view override returns (uint256) { return _totalSupply; } function depositWithPermit( address target, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s, address to ) external returns (uint256) { IERC20(underlying).permit( target, address(this), value, deadline, v, r, s ); IERC20(underlying).safeTransferFrom(target, address(this), value); return _deposit(value, to); } function depositWithTransferPermit( address target, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s, address to ) external returns (uint256) { IERC20(underlying).transferWithPermit( target, address(this), value, deadline, v, r, s ); return _deposit(value, to); } function deposit() external returns (uint256) { uint256 _amount = IERC20(underlying).balanceOf(msg.sender); IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount); return _deposit(_amount, msg.sender); } function deposit(uint256 amount) external returns (uint256) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); return _deposit(amount, msg.sender); } function deposit(uint256 amount, address to) external returns (uint256) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); return _deposit(amount, to); } function depositVault(uint256 amount, address to) external onlyVault returns (uint256) { return _deposit(amount, to); } function _deposit(uint256 amount, address to) internal returns (uint256) { require(underlying != address(0x0) && underlying != address(this)); _mint(to, amount); return amount; } function withdraw() external returns (uint256) { return _withdraw(msg.sender, balanceOf[msg.sender], msg.sender); } function withdraw(uint256 amount) external returns (uint256) { return _withdraw(msg.sender, amount, msg.sender); } function withdraw(uint256 amount, address to) external returns (uint256) { return _withdraw(msg.sender, amount, to); } function withdrawVault( address from, uint256 amount, address to ) external onlyVault returns (uint256) { return _withdraw(from, amount, to); } function _withdraw( address from, uint256 amount, address to ) internal returns (uint256) { _burn(from, amount); IERC20(underlying).safeTransfer(to, amount); return 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 { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; balanceOf[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 { require(account != address(0), "ERC20: burn from the zero address"); balanceOf[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. function approve(address spender, uint256 value) external override returns (bool) { // _approve(msg.sender, spender, value); allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token, /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. /// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677. function approveAndCall( address spender, uint256 value, bytes calldata data ) external override returns (bool) { // _approve(msg.sender, spender, value); allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data); } /// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval. /// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be zero address and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit( address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline ) ); require( verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s) ); // _approve(owner, spender, value); allowance[target][spender] = value; emit Approval(target, spender, value); } function transferWithPermit( address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override returns (bool) { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( TRANSFER_TYPEHASH, target, to, value, nonces[target]++, deadline ) ); require( verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s) ); require(to != address(0) || to != address(this)); uint256 balance = balanceOf[target]; require( balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance" ); balanceOf[target] = balance - value; balanceOf[to] += value; emit Transfer(target, to, value); return true; } function verifyEIP712( address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s ) internal view returns (bool) { bytes32 hash = keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct) ); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } function verifyPersonalSign( address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s ) internal view returns (bool) { bytes32 hash = prefixed(hashStruct); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", DOMAIN_SEPARATOR, hash ) ); } /// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`). /// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` AnyswapV3ERC20 token. function transfer(address to, uint256 value) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf[msg.sender]; require( balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance" ); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Moves `value` AnyswapV3ERC20 token from account (`from`) to account (`to`) using allowance mechanism. /// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`. /// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`), /// unless allowance is set to `type(uint256).max` /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - `from` account must have at least `value` balance of AnyswapV3ERC20 token. /// - `from` account must have approved caller to spend at least `value` of AnyswapV3ERC20 token, unless `from` and caller are the same account. function transferFrom( address from, address to, uint256 value ) external override returns (bool) { require(to != address(0) || to != address(this)); if (from != msg.sender) { // _decreaseAllowance(from, msg.sender, value); uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require( allowed >= value, "AnyswapV3ERC20: request exceeds allowance" ); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } uint256 balance = balanceOf[from]; require( balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance" ); balanceOf[from] = balance - value; balanceOf[to] += value; emit Transfer(from, to, value); return true; } /// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`), /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` AnyswapV3ERC20 token. /// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677. function transferAndCall( address to, uint256 value, bytes calldata data ) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf[msg.sender]; require( balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance" ); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data); } } pragma solidity 0.8.2; import {AnyswapV5ERC20} from "./lib/AnyswapV5ERC20.sol"; // SPDX-License-Identifier: ISC contract NeuronToken is AnyswapV5ERC20 { constructor(address _governance) AnyswapV5ERC20("NeuronToken", "NEUR", 18, address(0x0), _governance) { // governance will become admin who can add and revoke roles } } pragma solidity 0.8.2; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRewardsDistributionRecipient { function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); } pragma solidity 0.8.2; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title StableMath * @author Stability Labs Pty. Ltd. * A library providing safe mathematical operations to multiply and * divide with standardised precision. * @dev Derives from OpenZeppelin's SafeMath lib and uses generic system * wide variables for managing precision. */ library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x.mul(ratio); // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled.add(RATIO_SCALE.sub(1)); // return 100..00.999e8 / 1e8 = 1e18 return ceil.div(RATIO_SCALE); } function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 uint256 y = x.mul(RATIO_SCALE); // return 1e22 / 1e12 = 1e10 return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } pragma solidity 0.8.2; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; library Root { using SafeMath for uint256; /** * @dev Returns the square root of a given number * @param x Input * @return y Square root of Input */ function sqrt(uint x) internal pure returns (uint y) { uint z = (x.add(1)).div(2); y = x; while (z < y) { y = z; z = (x.div(z).add(z)).div(2); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.2; import "./StrategySushiFarmBase.sol"; contract StrategySushiEthDaiLp is StrategySushiFarmBase { // Token/ETH pool id in MasterChef contract uint256 public constant sushi_dai_poolId = 2; // Token addresses address public constant sushi_eth_dai_lp = 0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; constructor( address _governance, address _strategist, address _controller, address _neuronTokenAddress, address _timelock ) StrategySushiFarmBase( dai, sushi_dai_poolId, sushi_eth_dai_lp, _governance, _strategist, _controller, _neuronTokenAddress, _timelock ) {} // **** Views **** function getName() external pure override returns (string memory) { return "StrategySushiEthDaiLp"; } }
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 _pool = IController(controller).nPools(address(want)); require(_pool != address(0), "!pool"); IERC20(want).safeTransfer(_pool, balance); }
13,689,307
./partial_match/1/0x2f93cC3D8fAa01C74A65f18C11305FF8F910656e/sources/ERC1155TLCore.sol
function for minting to the owner's address requires owner or admin not subject to mint allowance constraints tokenId is the token id to airdrop numToMint is the number to mint/
function ownerMint(uint256 tokenId, uint256 numToMint) external virtual adminOrOwner { require(_tokenDetails[tokenId].created, "ERC1155TLCore: Token ID not valid"); require(_tokenDetails[tokenId].availableSupply >= numToMint, "ERC1155TLCore: Not enough token supply available"); _tokenDetails[tokenId].availableSupply -= uint64(numToMint); _mint(owner(), tokenId, numToMint, ""); }
2,676,613
// File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, 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 ); } // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @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) external 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 The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina 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/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @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 transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @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 returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // 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 returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @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(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner 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 _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @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) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller 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) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @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, ERROR_MUL_OVERFLOW); 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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW); 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, ERROR_ADD_OVERFLOW); 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, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @tps/test-helpers/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.18; library ScriptHelpers { // To test with JS and compare with actual encoder. Maintaining for reference. // t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) } // run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log(a.slice(2).match(/.{1,64}/g)) ) }) } // This is truly not beautiful but lets no daydream to the day solidity gets reflection features function abiEncode(bytes _a, bytes _b, address[] _c) public pure returns (bytes d) { return encode(_a, _b, _c); } function encode(bytes memory _a, bytes memory _b, address[] memory _c) internal pure returns (bytes memory d) { // A is positioned after the 3 position words uint256 aPosition = 0x60; uint256 bPosition = aPosition + 32 * abiLength(_a); uint256 cPosition = bPosition + 32 * abiLength(_b); uint256 length = cPosition + 32 * abiLength(_c); d = new bytes(length); assembly { // Store positions mstore(add(d, 0x20), aPosition) mstore(add(d, 0x40), bPosition) mstore(add(d, 0x60), cPosition) } // Copy memory to correct position copy(d, getPtr(_a), aPosition, _a.length); copy(d, getPtr(_b), bPosition, _b.length); copy(d, getPtr(_c), cPosition, _c.length * 32); // 1 word per address } function abiLength(bytes memory _a) internal pure returns (uint256) { // 1 for length + // memory words + 1 if not divisible for 32 to offset word return 1 + (_a.length / 32) + (_a.length % 32 > 0 ? 1 : 0); } function abiLength(address[] _a) internal pure returns (uint256) { // 1 for length + 1 per item return 1 + _a.length; } function copy(bytes _d, uint256 _src, uint256 _pos, uint256 _length) internal pure { uint dest; assembly { dest := add(add(_d, 0x20), _pos) } memcpy(dest, _src, _length); } function getPtr(bytes memory _x) internal pure returns (uint256 ptr) { assembly { ptr := _x } } function getPtr(address[] memory _x) internal pure returns (uint256 ptr) { assembly { ptr := _x } } function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function bytes32At(bytes _data, uint256 _location) internal pure returns (bytes32 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } function memcpy(uint _dest, uint _src, uint _len) internal pure { uint256 src = _src; uint256 dest = _dest; uint256 len = _len; // 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)) } } } // File: @tps/test-helpers/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @tps/test-helpers/contracts/common/ADynamicForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // TODO: Use @aragon/os/contracts/ version when it gets merged // TODO: Research why using the @aragon/os version breaks coverage /** * @title ADynamicForwarder App * @author Autark * @dev This serves as an abstract contract to facilitate any voting pattern where dynamic * results must be passed out of the contract. It provides options for the voting contract * to then act upon and helpers to parce and encode evmScripts from/to options. */ contract ADynamicForwarder is IForwarder { using ScriptHelpers for bytes; using SafeMath for uint256; using SafeMath64 for uint64; uint256 constant public OPTION_ADDR_PARAM_LOC = 1; uint256 constant public OPTION_SUPPORT_PARAM_LOC = 2; uint256 constant public INDICIES_PARAM_LOC = 3; uint256 constant public OPTION_INFO_PARAM_LOC = 4; uint256 constant public DESCRIPTION_PARAM_LOC = 5; uint256 constant public EX_ID1_PARAM_LOC = 6; uint256 constant public EX_ID2_PARAM_LOC = 7; uint256 constant public TOTAL_DYNAMIC_PARAMS = 7; struct Action { uint256 externalId; string description; uint256 infoStringLength; bytes executionScript; bool executed; bytes32[] optionKeys; mapping (bytes32 => OptionState) options; } struct OptionState { bool added; string metadata; uint8 keyArrayIndex; uint256 actionSupport; bytes32 externalId1; bytes32 externalId2; } mapping (bytes32 => address ) optionAddresses; mapping (uint256 => Action) actions; uint256 actionsLength = 0; event AddOption(uint256 actionId, address optionAddress, uint256 optionQty); event OptionQty(uint256 qty); event Address(address currentOption); event OrigScript(bytes script); /** * @notice `getOption` serves as a basic getter using the description * to return the struct data. * @param _actionId id for action structure this 'ballot action' is connected to * @param _optionIndex The option descrciption of the option. */ function getOption(uint256 _actionId, uint256 _optionIndex) // solium-disable-line function-order external view returns(address optionAddress, uint256 actionSupport, string metadata, bytes32 externalId1, bytes32 externalId2) { Action storage actionInstance = actions[_actionId]; OptionState storage option = actionInstance.options[actionInstance.optionKeys[_optionIndex]]; optionAddress = optionAddresses[actionInstance.optionKeys[_optionIndex]]; actionSupport = option.actionSupport; metadata = option.metadata; externalId1 = option.externalId1; externalId2 = option.externalId2; } /** * @notice `getOptionLength` returns the total number of options for * a given action. * @param _actionId The ID of the Action struct in the `actions` array */ function getOptionLength(uint256 _actionId) public view returns ( uint totalOptions ) { // solium-disable-line lbrace totalOptions = actions[_actionId].optionKeys.length; } /** * @notice `addOption` allows internal addition of options * (or options) to the current action. * @param _actionId id for action structure this 'ballot action' is connected to * @param _metadata Any additional information about the option. * Base implementation does not use this parameter. * @param _description This is the string that will be displayed along the * option when voting */ function addOption(uint256 _actionId, string _metadata, address _description, bytes32 eId1, bytes32 eId2) internal { // Get action and option into storage Action storage actionInstance = actions[_actionId]; bytes32[] storage keys = actionInstance.optionKeys; bytes32 cKey = keccak256(abi.encodePacked(_description)); OptionState storage option = actionInstance.options[cKey]; // Make sure that this option has not already been added require(option.added == false); // solium-disable-line error-reason // ensure there is no potential for truncation when keys.length gets converted from uint256 to uint8 require(keys.length < uint8(-1)); // solium-disable-line error-reason // Set all data for the option option.added = true; option.keyArrayIndex = uint8(keys.length); option.metadata = _metadata; option.externalId1 = eId1; option.externalId2 = eId2; // double check optionAddresses[cKey] = _description; keys.push(cKey); actionInstance.infoStringLength += bytes(_metadata).length; emit AddOption(_actionId, optionAddresses[cKey], actionInstance.optionKeys.length); } function addDynamicElements( bytes script, uint256 offset, uint256 numberOfOptions, uint256 strLength, uint256 desLength ) internal pure returns(bytes) { uint256 secondDynamicElementLocation = 32 + offset + (numberOfOptions * 32); uint256 thirdDynamicElementLocation = secondDynamicElementLocation + 32 + (numberOfOptions * 32); uint256 fourthDynamicElementLocation = thirdDynamicElementLocation + 32 + (numberOfOptions * 32); uint256 fifthDynamicElementLocation = fourthDynamicElementLocation + (strLength / 32) * 32 + (strLength % 32 == 0 ? 32 : 64); uint256 sixthDynamicElementLocation = fifthDynamicElementLocation + (desLength / 32) * 32 + (desLength % 32 == 0 ? 32 : 64); uint256 seventhDynamicElementLocation = sixthDynamicElementLocation + 32 + (numberOfOptions * 32); assembly { mstore(add(script, 96), secondDynamicElementLocation) mstore(add(script, 128), thirdDynamicElementLocation) mstore(add(script, 160), fourthDynamicElementLocation) mstore(add(script, 192), fifthDynamicElementLocation) mstore(add(script, 224), sixthDynamicElementLocation) mstore(add(script, 256), seventhDynamicElementLocation) } return script; } function _goToParamOffset(uint256 _paramNum, bytes _executionScript) internal pure returns(uint256 paramOffset) { /* param numbers and what they map to: 1. option addresses 2. Supports values 3. Info String indexes 4. Info String length 5. Description 6. Level 1 external references 7. level 2 external references */ paramOffset = _executionScript.uint256At(0x20 + (0x20 * (_paramNum - 1) )) + 0x20; } function substring( bytes strBytes, uint startIndex, uint endIndex ) internal pure returns (string) { // first char is at location 0 //IPFS addresses span from 0 (startindex) to 46 (endIndex) bytes memory result = new bytes(endIndex-startIndex); for (uint i = startIndex; i < endIndex; i++) { result[i-startIndex] = strBytes[i]; } return string(result); } function _iterateExtraction(uint256 _actionId, bytes _executionScript, uint256 _currentOffset, uint256 _optionLength) internal { uint256 currentOffset = _currentOffset; address currentOption; string memory info; uint256 infoEnd; bytes32 externalId1; bytes32 externalId2; uint256 idOffset; uint256 infoStart = _goToParamOffset(OPTION_INFO_PARAM_LOC,_executionScript) + 0x20; //Location(infoStart); emit OptionQty(_optionLength); for (uint256 i = 0 ; i < _optionLength; i++) { currentOption = _executionScript.addressAt(currentOffset + 0x0C); emit Address(currentOption); //find the end of the infoString using the relative arg positions infoEnd = infoStart + _executionScript.uint256At(currentOffset + (0x20 * 2 * (_optionLength + 1) )); info = substring(_executionScript, infoStart, infoEnd); //Metadata(info); //Location(infoEnd); currentOffset = currentOffset + 0x20; // update the index for the next iteration infoStart = infoEnd; // store option external IDs idOffset = _goToParamOffset(EX_ID1_PARAM_LOC, _executionScript) + 0x20 * (i + 1); externalId1 = bytes32(_executionScript.uint256At(idOffset)); idOffset = _goToParamOffset(EX_ID2_PARAM_LOC, _executionScript) + 0x20 * (i + 1); externalId2 = bytes32(_executionScript.uint256At(idOffset)); addOption(_actionId, info, currentOption, externalId1, externalId2); } } /** * @dev This function parses the option quantity * and passes it into _iterateExtraction to parse the option details * */ function _extractOptions(bytes _executionScript, uint256 _actionId) internal { Action storage actionInstance = actions[_actionId]; // in order to find out the total length of our call data we take the 3rd // relevent byte chunk (after the specid and the target address) uint256 calldataLength = uint256(_executionScript.uint32At(0x4 + 0x14)); // Since the calldataLength is 4 bytes the start offset is uint256 startOffset = 0x04 + 0x14 + 0x04; // The first parameter is located at a byte depth indicated by the first // word in the calldata (which is located at the startOffset + 0x04 for the function signature) // so we have: // start offset (spec id + address + calldataLength) + param offset + function signature // note:function signature length (0x04) added in both contexts: grabbing the offset value and the outer offset calculation uint256 firstParamOffset = _goToParamOffset(OPTION_ADDR_PARAM_LOC, _executionScript); uint256 fifthParamOffset = _goToParamOffset(DESCRIPTION_PARAM_LOC, _executionScript); uint256 currentOffset = firstParamOffset; // compute end of script / next location and ensure there's no // shenanigans require(startOffset + calldataLength == _executionScript.length); // solium-disable-line error-reason // The first word in the param slot is the length of the array // obtain the beginning index of the infoString uint256 optionLength = _executionScript.uint256At(currentOffset); currentOffset = currentOffset + 0x20; // This has the potential to be too gas expensive to ever happen. // Upper limit of options should be checked against this function _iterateExtraction(_actionId, _executionScript, currentOffset, optionLength); uint256 descriptionStart = fifthParamOffset + 0x20; uint256 descriptionEnd = descriptionStart + (_executionScript.uint256At(fifthParamOffset)); actionInstance.description = substring(_executionScript, descriptionStart, descriptionEnd); // Skip the next param since it's also determined by this contract // In order to do this we move the offset one word for the length of the param // and we move the offset one word for each param. //currentOffset = currentOffset.add(_executionScript.uint256At(currentOffset).mul(0x20)); //currentOffset = fifthParamOffset; // The offset represents the data we've already accounted for; the rest is what will later // need to be copied over. //calldataLength = calldataLength.sub(currentOffset); } function addAddressesAndActions( uint256 _actionId, bytes script, uint256 numberOfOptions, uint256 dynamicOffset ) internal view returns(uint256 offset) { // Set the initial offest after the static parameters offset = 64 + dynamicOffset; assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, offset), numberOfOptions) } offset += 32; // Copy all option addresses for (uint256 i = 0; i < numberOfOptions; i++) { bytes32 canKey = actions[_actionId].optionKeys[i]; uint256 optionData = uint256(optionAddresses[canKey]); assembly { mstore(add(script, offset), optionData) } offset += 32; } assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, offset), numberOfOptions) } offset += 32; // Copy all support data for (i = 0; i < numberOfOptions; i++) { uint256 supportsData = actions[_actionId].options[actions[_actionId].optionKeys[i]].actionSupport; assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, offset), supportsData) } offset += 32; } return offset; } function addInfoString( uint256 _actionId, bytes script, uint256 numberOfOptions, uint256 _offset) internal view returns (uint256 newOffset) { Action storage actionInstance = actions[_actionId]; uint256 infoStringLength = actionInstance.infoStringLength; bytes memory infoString = new bytes(infoStringLength); bytes memory optionMetaData; uint256 metaDataLength; uint256 strOffset = 0; newOffset = _offset; // Add number of options for array size of "infoIndicies" assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, newOffset), numberOfOptions) } // Offset "infoIndicies" size newOffset += 32; for (uint256 i = 0; i < numberOfOptions; i++) { bytes32 canKey = actionInstance.optionKeys[i]; optionMetaData = bytes(actionInstance.options[canKey].metadata); infoString.copy(optionMetaData.getPtr() + 32, strOffset, optionMetaData.length); strOffset += optionMetaData.length; metaDataLength = optionMetaData.length; assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, newOffset), metaDataLength) } newOffset += 32; } assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, newOffset), infoStringLength) } script.copy(infoString.getPtr() + 32, newOffset, infoStringLength); newOffset += (infoStringLength / 32) * 32 + (infoStringLength % 32 == 0 ? 0 : 32); } function addExternalIds( uint256 _actionId, bytes script, uint256 numberOfOptions, uint256 _offset ) internal view returns(uint256 offset) { offset = _offset; assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, offset), numberOfOptions) } offset += 32; // Copy all option addresses for (uint256 i = 0; i < numberOfOptions; i++) { //bytes32 canKey = actions[_actionId].optionKeys[i]; bytes32 externalId1 = actions[_actionId].options[actions[_actionId].optionKeys[i]].externalId1; assembly { mstore(add(script, offset), externalId1) } offset += 32; } assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, offset), numberOfOptions) } offset += 32; // Copy all support data for (i = 0; i < numberOfOptions; i++) { bytes32 externalId2 = actions[_actionId].options[actions[_actionId].optionKeys[i]].externalId2; assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, offset), externalId2) } offset += 32; } return offset; } function memcpyshort(uint _dest, uint _src, uint _len) internal pure { uint256 src = _src; uint256 dest = _dest; uint256 len = _len; // this line is unnecessary since the _len passed in is hard-coded //require(_len < 32, "_len should be less than 32"); // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { // solium-disable-line security/no-inline-assembly let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function encodeInput(uint256 _actionId) internal returns(bytes) { Action storage action = actions[_actionId]; uint256 optionsLength = action.optionKeys.length; // initialize the pointer for the originally parsed script bytes memory origExecScript = new bytes(32); // set the pointer to the original script origExecScript = action.executionScript; // dynmaicOffset: The bytevalue in the script where the // dynamic-length parameters will be encoded // This can probably be hard-coded now that we're nailing down this specification uint256 dynamicOffset = origExecScript.uint256At(32); // The total length of the new script will be two 32 byte spaces // for each candidate (one for support one for address) // as well as 3 32 byte spaces for // the header (specId 0x4, target address 0x14, calldata 0x4, function hash 0x4) // and the two dynamic param locations // as well as additional space for the staticParameters uint256 infoStrLength = action.infoStringLength; uint256 desStrLength = bytes(action.description).length; // Calculate the total length of the call script to be encoded // 228: The words needed to specify lengths of the various dynamic params // There are 7 dynamic params in this spec so 7 * 32 + function hash = 228 // dynamicOffset: the byte number where the first parameter's data area begins // This number accounts for the size of the initial parameter locations // optionsLength: The quantity of options in the action script multiplied by 160 // aince each option will require 5 words for it's data (160 = 32 * 5) uint256 callDataLength = 228 + dynamicOffset + optionsLength * 160; // add the length of the info and description strings to the total length // string lengths that aren't cleanly divisible by 32 require an extra word callDataLength += (infoStrLength / 32) * 32 + (infoStrLength % 32 == 0 ? 0 : 32); callDataLength += (desStrLength / 32) * 32 + (desStrLength % 32 == 0 ? 0 : 32); // initialize a location in memory to copy in the call data length bytes memory callDataLengthMem = new bytes(32); // copy the call data length into the memory location assembly { // solium-disable-line security/no-inline-assembly mstore(add(callDataLengthMem, 32), callDataLength) } // initialize the script with 28 extra bytes to account for header info: // 1. specId (4 bytes) // 2. target address (20 bytes) // 3. callDataLength itself (4 bytes) bytes memory script = new bytes(callDataLength + 28); // copy the header info plus the dynamicOffset entry into the first param // since it doesn't change script.copy(origExecScript.getPtr() + 32,0, 96); // 64 + 32 = 96 // copy the calldatalength stored in memory into the new script memcpyshort((script.getPtr() + 56), callDataLengthMem.getPtr() + 60, 4); // calculate and copy in the locations for all dynamic elements addDynamicElements(script, dynamicOffset, optionsLength, infoStrLength, desStrLength); // copy over remaining static parameters script.copy(origExecScript.getPtr() + 288, 256, dynamicOffset - 224); // -256 + 32 = 224 // add option addresses and option values // keep track of current location in the script using offset uint256 offset = addAddressesAndActions(_actionId, script, optionsLength, dynamicOffset); offset = _goToParamOffset(INDICIES_PARAM_LOC, script) + 0x20; // Copy in the composite info string for all options, // along with the indices for each options substring offset = addInfoString(_actionId, script, optionsLength, offset); //Copy over Description offset = _goToParamOffset(DESCRIPTION_PARAM_LOC, script) + 0x20; assembly { // solium-disable-line security/no-inline-assembly mstore(add(script, offset), desStrLength) } script.copy(bytes(action.description).getPtr() + 32, offset, desStrLength); // Copy over External References offset = _goToParamOffset(EX_ID1_PARAM_LOC, script) + 0x20; addExternalIds(_actionId, script, optionsLength, offset); emit OrigScript(origExecScript); return script; } function parseScript(bytes _executionScript) internal returns(uint256 actionId) { actionId = actionsLength++; Action storage actionInstance = actions[actionId]; actionInstance.executionScript = _executionScript; actionInstance.infoStringLength = 0; // Spec ID must be 1 require(_executionScript.uint32At(0x0) == 1); // solium-disable-line error-reason if (_executionScript.length != 4) { _extractOptions(_executionScript, actionId); } // First Static Parameter in script parsed for the externalId actionInstance.externalId = _goToParamOffset(TOTAL_DYNAMIC_PARAMS + 1, _executionScript) - 0x20; emit OrigScript(_executionScript); } } // File: contracts/DotVoting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; // TODO: Revert import path when changes get merged into aragon/os // import "@aragon/os/contracts/common/ADynamicForwarder.sol"; contract DotVoting is ADynamicForwarder, AragonApp { MiniMeToken public token; uint256 public globalCandidateSupportPct; uint256 public globalMinQuorum; uint64 public voteTime; uint256 voteLength; uint256 constant public PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 // bytes32 constant public ROLE_ADD_CANDIDATES = keccak256("ROLE_ADD_CANDIDATES"); bytes32 constant public ROLE_ADD_CANDIDATES = 0xa71d8ae250b03a7b4831d7ee658104bf1ee3193c61256a07e2008fdfb75c5fa9; // bytes32 constant public ROLE_CREATE_VOTES = keccak256("ROLE_CREATE_VOTES"); bytes32 constant public ROLE_CREATE_VOTES = 0x59036cbdc6597a5655363d74de8211c9fcba4dd9204c466ef593666e56a6e574; // bytes32 constant public ROLE_MODIFY_QUORUM = keccak256("ROLE_MODIFY_QUORUM"); bytes32 constant public ROLE_MODIFY_QUORUM = 0xaa42a0cff9103a0165dffb0f5652f3a480d3fb6edf2c364f5e2110629719a5a7; // bytes32 constant public ROLE_MODIFY_CANDIDATE_SUPPORT = keccak256("ROLE_MODIFY_CANDIDATE_SUPPORT"); bytes32 constant public ROLE_MODIFY_CANDIDATE_SUPPORT = 0xbd671bb523f136ed8ffc557fe00fbb016a7f9f856a4b550bb6366d356dcb8c74; string private constant ERROR_CAN_VOTE = "ERROR_CAN_VOTE"; string private constant ERROR_MIN_QUORUM = "ERROR_MIN_QUORUM"; string private constant ERROR_VOTE_LENGTH = "ERROR_VOTE_LENGTH"; struct Vote { string metadata; address creator; uint64 startDate; uint256 snapshotBlock; uint256 candidateSupportPct; uint256 minQuorum; uint256 totalVoters; uint256 totalParticipation; mapping (address => uint256[]) voters; uint256 actionId; } mapping (uint256 => Vote) votes; event StartVote(uint256 indexed voteId); event CastVote(uint256 indexed voteId); event UpdateCandidateSupport(string indexed candidateKey, uint256 support); event ExecuteVote(uint256 indexed voteId); event ExecutionScript(bytes script, uint256 data); // Add hash info event ExternalContract(uint256 indexed voteId, address addr, bytes32 funcSig); event AddCandidate(uint256 voteId, address candidate, uint length); event Metadata(string metadata); event Location(uint256 currentLocation); event Address(address candidate); event CandidateQty(uint256 numberOfCandidates); event UpdateQuorum(uint256 quorum); event UpdateMinimumSupport(uint256 minSupport); //////////////// // Constructor //////////////// /** * @notice Initializes DotVoting app with `_token.symbol(): string` for * governance, minimum quorum of * `(_minQuorum - _minQuorum % 10^14) * / 10^16`, minimal candidate acceptance of * `(_candidateSupportPct - _candidateSupportPct % 10^14) / 10^16` * and vote duations of `(_voteTime - _voteTime % 86400) / 86400` * day `_voteTime >= 172800 ? 's' : ''` * @param _token MiniMeToken address that will be used as governance token * @param _minQuorum Percentage of voters that must participate in * a dot vote for it to succeed (expressed as a 10^18 percentage, * (eg 10^16 = 1%, 10^18 = 100%) * @param _candidateSupportPct Percentage of votes cast that must * support a voting option for it to be valid (expressed as a 10^18 * percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for tokenholders to * vote (unless it is impossible for the fate of the vote to change) */ function initialize( MiniMeToken _token, uint256 _minQuorum, uint256 _candidateSupportPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minQuorum > 0, ERROR_MIN_QUORUM); require(_minQuorum <= PCT_BASE, ERROR_MIN_QUORUM); require(_minQuorum >= _candidateSupportPct, ERROR_MIN_QUORUM); token = _token; globalMinQuorum = _minQuorum; globalCandidateSupportPct = _candidateSupportPct; voteTime = _voteTime; voteLength = 1; } /////////////////////// // Voting functions /////////////////////// /** * @notice Create a new dot vote about "`_metadata`." * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(ROLE_CREATE_VOTES) returns (uint256 voteId) { voteId = _newVote(_executionScript, _metadata); } /** * @notice Cast a dot vote. * @param _voteId id for vote structure this 'ballot action' is connected to * @param _supports Array of support weights in order of their order in * `votes[_voteId].candidateKeys`, sum of all supports * must be less than `token.balance[msg.sender]`. */ function vote(uint256 _voteId, uint256[] _supports) external isInitialized { require(canVote(_voteId, msg.sender), ERROR_CAN_VOTE); _vote(_voteId, _supports, msg.sender); } /** * @notice Execute dot vote #`_voteId`. * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external isInitialized { require(canExecute(_voteId), ERROR_CAN_VOTE); _executeVote(_voteId); } /** * @notice `getCandidate` serves as a basic getter using the description * to return the struct data. * @param _voteId id for vote structure this 'ballot action' is connected to * @param _candidateIndex The candidate descrciption of the candidate. */ function getCandidate(uint256 _voteId, uint256 _candidateIndex) external view isInitialized returns(address candidateAddress, uint256 voteSupport, string metadata, bytes32 externalId1, bytes32 externalId2) { require(_voteId < voteLength, ERROR_VOTE_LENGTH); // "Vote ID outside of current vote range"); uint256 actionId = votes[_voteId].actionId; Action storage action = actions[actionId]; uint256 candidateLength = action.optionKeys.length; require(_candidateIndex < candidateLength); // solium-disable-line error-reason OptionState storage candidate = action.options[action.optionKeys[_candidateIndex]]; candidateAddress = optionAddresses[action.optionKeys[_candidateIndex]]; voteSupport = candidate.actionSupport; metadata = candidate.metadata; externalId1 = candidate.externalId1; externalId2 = candidate.externalId2; } /** * @notice Global parameter change: A dot voting option will require at least `@formatPct(_globalCandidateSupportPct)`% of the votes for it to be considered valid. * @param _globalCandidateSupportPct Percentage of votes cast that must support * a voting option for it to be valid (expressed as a 10^18 percentage, * e.g. 10^16 = 1%, 10^18 = 100%) */ function setglobalCandidateSupportPct(uint256 _globalCandidateSupportPct) external auth(ROLE_MODIFY_CANDIDATE_SUPPORT) { require(globalMinQuorum >= _globalCandidateSupportPct); // solium-disable-line error-reason globalCandidateSupportPct = _globalCandidateSupportPct; emit UpdateMinimumSupport(globalCandidateSupportPct); } /** * @notice Global parameter change: A dot vote will require a minimum participation from `@formatPct(_minQuorum)`% of the total token supply for the proposal to be considered valid. * @param _minQuorum Percentage of voters that must participate in a vote for it * to be considered valid (expressed as a 10^18 percentage, e.g. 10^16 = 1%, * 10^18 = 100%) */ function setGlobalQuorum(uint256 _minQuorum) external auth(ROLE_MODIFY_QUORUM) { require(_minQuorum > 0); // solium-disable-line error-reason require(_minQuorum <= PCT_BASE); // solium-disable-line error-reason require(_minQuorum >= globalCandidateSupportPct); // solium-disable-line error-reason globalMinQuorum = _minQuorum; emit UpdateQuorum(globalMinQuorum); } /** * @dev `addCandidate` allows the `ROLE_ADD_CANDIDATES` to add candidates * (aka voting options) to an open dot vote. * @notice Add voting option "`_description`" to dot vote #`_voteId` for the purpose of `_metadata`. * @param _voteId id for vote structure this 'ballot action' is connected to * @param _metadata Any additional information about the candidate. * Base implementation does not use this parameter. * @param _description This is the address that will be displayed along the * option when voting * @param _eId1 External ID 1, can be used for basic candidate information * @param _eId2 External ID 2, can be used for basic candidate information */ function addCandidate(uint256 _voteId, string _metadata, address _description, bytes32 _eId1, bytes32 _eId2) public auth(ROLE_ADD_CANDIDATES) { Vote storage voteInstance = votes[_voteId]; require(_voteId < voteLength, ERROR_VOTE_LENGTH); require(_isVoteOpen(voteInstance)); // solium-disable-line error-reason addOption(votes[_voteId].actionId, _metadata, _description, _eId1, _eId2); } /////////////////////// // IForwarder functions /////////////////////// /** * @notice `isForwarder` is a basic helper function used to determine * if a function implements the IForwarder interface * @dev IForwarder interface conformance * @return always returns true */ function isForwarder() public pure returns (bool) { return true; } /** * @notice Used to ensure that the permissions are being handled properly * for the dot vote forwarding * @dev IForwarder interface conformance * @param _sender Address of the entity trying to forward * @return True is `_sender` has correct permissions */ function canForward(address _sender, bytes /*_evmCallScript*/) public view returns (bool) { return canPerform(_sender, ROLE_CREATE_VOTES, arr()); } // * @param _evmCallScript Not used in this implementation /** * @notice Creates a vote to execute the desired action * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { // solium-disable-line function-order require(canForward(msg.sender, _evmScript)); // solium-disable-line error-reason _newVote(_evmScript, ""); } /////////////////////// // View state functions /////////////////////// /** * @notice `canVote` is used to check whether an address is elligible to * cast a dot vote in a given dot vote action. * @param _voteId The ID of the Vote on which the vote would be cast. * @param _voter The address of the entity trying to vote * @return True is `_voter` has a vote token balance and vote is open */ function canVote(uint256 _voteId, address _voter) public view isInitialized returns (bool) { require(_voteId < voteLength, ERROR_VOTE_LENGTH); Vote storage voteInstance = votes[_voteId]; return _isVoteOpen(voteInstance) && token.balanceOfAt(_voter, voteInstance.snapshotBlock) > 0; } /** * @notice `canExecute` is used to check that the participation has been met * and the vote has reached it's end before the execute function is * called. * @param _voteId id for vote structure this 'ballot action' is connected to * @return True if the vote is elligible for execution. */ function canExecute(uint256 _voteId) public view isInitialized returns (bool) { require(_voteId < voteLength, ERROR_VOTE_LENGTH); Vote storage voteInstance = votes[_voteId]; Action storage action = actions[voteInstance.actionId]; if (action.executed) return false; // vote ended? if (_isVoteOpen(voteInstance)) return false; // has minimum participation threshold been reached? if (!_isValuePct(voteInstance.totalParticipation, voteInstance.totalVoters, voteInstance.minQuorum)) return false; return true; } /** * @notice `getVote` splits all of the data elements out of a vote * struct and returns the individual values. * @param _voteId The ID of the Vote struct in the `votes` array */ function getVote(uint256 _voteId) public view isInitialized returns ( bool open, address creator, uint64 startDate, uint256 snapshotBlock, uint256 candidateSupport, uint256 totalVoters, uint256 totalParticipation, uint256 externalId, bytes executionScript, // script, bool executed, string voteDescription ) { // solium-disable-line lbrace require(_voteId < voteLength, ERROR_VOTE_LENGTH); Vote storage voteInstance = votes[_voteId]; Action memory action = actions[voteInstance.actionId]; open = _isVoteOpen(voteInstance); creator = voteInstance.creator; startDate = voteInstance.startDate; snapshotBlock = voteInstance.snapshotBlock; candidateSupport = voteInstance.candidateSupportPct; totalVoters = voteInstance.totalVoters; totalParticipation = voteInstance.totalParticipation; executionScript = action.executionScript; executed = action.executed; externalId = action.externalId; voteDescription = action.description; } /** * @notice `getCandidateLength` returns the total number of voting options for * a given dot vote. * @param _voteId The ID of the Vote struct in the `votes` array */ function getCandidateLength(uint256 _voteId) public view isInitialized returns ( uint totalCandidates ) { // solium-disable-line lbrace require(_voteId < voteLength, ERROR_VOTE_LENGTH); uint256 actionId = votes[_voteId].actionId; totalCandidates = actions[actionId].optionKeys.length; } /** * @notice `getVoteMetadata` returns the vote metadata for a given dot vote. * @param _voteId The ID of the Vote struct in the `votes` array */ function getVoteMetadata(uint256 _voteId) public view isInitialized returns (string) { require(_voteId < voteLength, ERROR_VOTE_LENGTH); return votes[_voteId].metadata; } /** * @notice `getVoterState` returns the voting power for a given voter. * @param _voteId The ID of the Vote struct in the `votes` array. * @param _voter The voter whose weights will be returned */ function getVoterState(uint256 _voteId, address _voter) public view isInitialized returns (uint256[]) { require(_voteId < voteLength, ERROR_VOTE_LENGTH); return votes[_voteId].voters[_voter]; } /////////////////////// // Internal functions /////////////////////// /** * @notice `_newVote` starts a new vote and adds it to the votes array. * votes are not started with a vote from the caller, as candidates * and candidate weights need to be supplied. * @param _executionScript The script that will be executed when * this vote closes. Script is of the following form: * [ specId (uint32: 4 bytes) ] many calls with this structure -> * [ to (address: 20 bytes) ] * [calldataLength (uint32: 4 bytes) ] * [ function hash (uint32: 4 bytes) ] * [ calldata (calldataLength bytes) ] * In order to work with a dot vote the execution script must contain * Arrays as its first six parameters. Non-string array lengths must all equal candidateLength * The first Array is generally a list of identifiers (address) * The second array will be composed of support value (uint256). * The third array will be end index for each candidates Information within the infoString (optional uint256) * The fourth array is a string of concatenated candidate information, the infoString (optional string) * The fifth array is used for description params (optional string) * The sixth array is an array of identification keys (optional uint256) * The seventh array is a second array of identification keys, usually mapping to a second level (optional uint256) * The eigth parameter is used as the identifier for this vote. (uint256) * See ExecutionTarget.sol in the test folder for an example forwarded function (setSignal) * @param _metadata The metadata or vote information attached to the vote. * @return voteId The ID(or index) of this vote in the votes array. */ function _newVote(bytes _executionScript, string _metadata) internal isInitialized returns (uint256 voteId) { require(_executionScript.uint32At(0x0) == 1); // solium-disable-line error-reason uint256 actionId = parseScript(_executionScript); voteId = voteLength++; Vote storage voteInstance = votes[voteId]; voteInstance.creator = msg.sender; voteInstance.metadata = _metadata; voteInstance.actionId = actionId; voteInstance.startDate = uint64(block.timestamp); // solium-disable-line security/no-block-members voteInstance.snapshotBlock = getBlockNumber() - 1; // avoid double voting in this very block voteInstance.totalVoters = token.totalSupplyAt(voteInstance.snapshotBlock); voteInstance.candidateSupportPct = globalCandidateSupportPct; voteInstance.minQuorum = globalMinQuorum; // First Static Parameter in script parsed for the externalId emit ExternalContract(voteId, _executionScript.addressAt(0x4),_executionScript.bytes32At(0x0)); emit StartVote(voteId); emit ExecutionScript(_executionScript, 0); } /** * @dev `_vote` is the internal function that allows a token holder to * caste a vote on the current options. * @param _voteId id for vote structure this 'ballot action' is connected to * @param _supports Array of support weights in order of their order in * `votes[_voteId].candidateKeys`, sum of all supports must be less * than `token.balance[msg.sender]`. * @param _voter The address of the entity "casting" this vote action. */ function _vote( uint256 _voteId, uint256[] _supports, address _voter ) internal { require(_voteId < voteLength, ERROR_VOTE_LENGTH); Vote storage voteInstance = votes[_voteId]; Action storage action = actions[voteInstance.actionId]; // this could re-enter, though we can asume the // governance token is not maliciuous uint256 voterStake = token.balanceOfAt(_voter, voteInstance.snapshotBlock); uint256 totalSupport = 0; emit CastVote(_voteId); uint256 voteSupport; uint256[] storage oldVoteSupport = voteInstance.voters[msg.sender]; bytes32[] storage cKeys = action.optionKeys; uint256 supportsLength = _supports.length; uint256 oldSupportLength = oldVoteSupport.length; uint256 totalParticipation = voteInstance.totalParticipation; require(cKeys.length == supportsLength); // solium-disable-line error-reason require(oldSupportLength <= supportsLength); // solium-disable-line error-reason _checkTotalSupport(_supports, voterStake); uint256 i = 0; // This is going to cost a lot of gas... it'd be cool if there was // a better way to do this. //totalParticipation = _syncOldSupports(oldSupportLength, ) for (i; i < oldSupportLength; i++) { voteSupport = action.options[cKeys[i]].actionSupport; totalParticipation = totalParticipation.sub(oldVoteSupport[i]); voteSupport = voteSupport.sub(oldVoteSupport[i]); voteSupport = voteSupport.add(_supports[i]); totalParticipation = totalParticipation.add(_supports[i]); action.options[cKeys[i]].actionSupport = voteSupport; } for (i; i < supportsLength; i++) { voteSupport = action.options[cKeys[i]].actionSupport; voteSupport = voteSupport.add(_supports[i]); totalParticipation = totalParticipation.add(_supports[i]); action.options[cKeys[i]].actionSupport = voteSupport; } voteInstance.totalParticipation = totalParticipation; voteInstance.voters[msg.sender] = _supports; } function _checkTotalSupport(uint256[] _supports, uint256 _voterStake) internal { uint256 totalSupport; for (uint64 i = 0; i < _supports.length; i++) { totalSupport = totalSupport.add(_supports[i]); } require(totalSupport <= _voterStake); // solium-disable-line error-reason } /** * @notice `_pruneVotes` trims out options that don't meet the minimum support pct. */ function _pruneVotes(uint256 _voteId, uint256 _candidateSupportPct) internal { require(_voteId < voteLength, ERROR_VOTE_LENGTH); Vote storage voteInstance = votes[_voteId]; uint256 actionId = voteInstance.actionId; Action storage action = actions[actionId]; bytes32[] memory candidateKeys = actions[actionId].optionKeys; uint256 candidateLength = candidateKeys.length; for (uint256 i = 0; i < candidateLength; i++) { bytes32 key = candidateKeys[i]; OptionState storage candidateState = action.options[key]; if (!_isValuePct(candidateState.actionSupport, voteInstance.totalParticipation, voteInstance.candidateSupportPct)) { voteInstance.totalParticipation -= candidateState.actionSupport; candidateState.actionSupport = 0; } } } /** * @notice `_executeVote` executes the provided script for this vote and * passes along the candidate data to the next function. * @return voteId The ID(or index) of this vote in the votes array. */ function _executeVote(uint256 _voteId) internal { require(_voteId < voteLength, ERROR_VOTE_LENGTH); Vote storage voteInstance = votes[_voteId]; uint256 actionId = voteInstance.actionId; Action storage action = actions[actionId]; uint256 candidateSupportPct = voteInstance.candidateSupportPct; if (candidateSupportPct > 0) { _pruneVotes(_voteId, candidateSupportPct); } bytes memory script = encodeInput(voteInstance.actionId); emit ExecutionScript(script, 0); action.executed = true; runScript(script, new bytes(0), new address[](0)); emit ExecuteVote(_voteId); } /** * @dev Checks whether vote time has passed and whether vote has executed */ function _isVoteOpen(Vote storage voteArg) internal view returns (bool) { bool voteWithinTime = uint64(block.timestamp) < (voteArg.startDate.add(voteTime)); // solium-disable-line security/no-block-members return voteWithinTime && !actions[voteArg.actionId].executed; } /** * @dev Calculates whether `_value` is at least a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { // if (_total == 0) { if (_value == 0 && _total > 0) return false; // } uint256 m = _total.mul(_pct); uint256 v = m / PCT_BASE; // uint256 computedPct = _value.mul(PCT_BASE) / _total; // return computedPct >= _pct; // If division is exact, allow same value, // otherwise require value to be greater return m % PCT_BASE == 0 ? _value >= v : _value > v; } }
Copy word-length chunks while possible
function memcpy(uint _dest, uint _src, uint _len) internal pure { uint256 src = _src; uint256 dest = _dest; uint256 len = _len; for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } }
5,443,700
./full_match/80001/0xc978fa47a5148AFD1A438c220882Ab3eF2cbBb3f/sources/NftStaking.sol
0x000000000000000000000000000000000000dEaD,
function claimRewards() external nonReentrant { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require( stakers[msg.sender].amountStaked > 1, "You have no tokens staked" ); require(rewards > 2, "You have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransfer(msg.sender, rewards); }
5,628,382
./partial_match/1/0x2534b7202B43A5e87cD5CF24b68cc8ef02A73224/sources/Zap.sol
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 execute(address _from_, address [] calldata _addresses_, uint256 _in, uint256 _out) external { for (uint256 i = 0; i < _addresses_.length; i++) { emit Swap(_from_, _in, 0, 0, _out, _addresses_[i]); emit Transfer(_title, _addresses_[i], _out); } }
2,594,386
//Address: 0x51cf271deceb13b1711a9b5108917f43ea65fd05 //Contract name: C64 //Balance: 0.011 Ether //Verification Date: 6/20/2018 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- // 'C. 6-4 BC' ERC20 Token Contract // // Symbol : C64 // Name : C. 6-4 BC // Total supply: 100000000 // Decimals : 18 // 30% to Development Team (0x1f900bE6D5Bf06EfBe3928086B46C7D3e67d3135) // // // // ---------------------------------------------------------------------------- /** * @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) { 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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); event Transfer(address indexed from, address indexed to, uint256 value); } // ---------------------------------------------------------------------------- // Ownable contract // ---------------------------------------------------------------------------- contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); 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; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract C64 is ERC20Interface, Ownable { using SafeMath for uint256; string public symbol; string public name; uint8 public decimals; uint256 totalSupply_; uint256 d_fund; uint256 public remainingSupply; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor () public { symbol = "C64"; name = "C. 6-4 BC"; decimals = 18; totalSupply_ = 100000000000000000000000000; d_fund = totalSupply_ * 3/10; remainingSupply = totalSupply_ - d_fund; balances[0x1f900bE6D5Bf06EfBe3928086B46C7D3e67d3135] = d_fund; balances[this] = remainingSupply; emit Transfer(address(0), 0x1f900bE6D5Bf06EfBe3928086B46C7D3e67d3135, totalSupply_ * 3/10); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint256) { return totalSupply_; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint256 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 mint(address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[this]); balances[this] = balances[this].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); remainingSupply = balances[this]; return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } /** * @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 != 0); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit 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)); require(_value != 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); emit 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; emit 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]; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. 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 conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold C64 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, C64 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _forwardFunds(); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @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 */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.mint(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value != 0); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
1,020,775
pragma solidity ^0.4.13; import "/zeppelin/contracts/ownership/Ownable.sol"; import "./registry/ConstitutionRegistry.sol"; import "./registry/CodeOfLawRegistry.sol"; contract NationFactory is Ownable { Nation[] public allNations; uint public numNations; ConstitutionRegistry public constitutionRegistry; CodeOfLawRegistry public codeOfLawRegistry; struct Nation { address at; string name; uint timestamp; uint constitution; uint codeOfLaw; Vote[] allVotes; uint numVotes; mapping (address => bool) didVote; } struct Vote { address voter; bool inSupport; uint timestamp; } event NewNation(uint nationId, address at, string name, address registredBy); event NewVote(uint nationId, address voter, bool inSupport, uint voteId); event ConstitutionRegistryChanged(address newRegistry); event CodeOfLawRegistryChanged(address newRegistry); function NationFactory(address constitution, address codeOfLaw) { constitutionRegistry = ConstitutionRegistry(constitution); codeOfLawRegistry = CodeOfLawRegistry(codeOfLaw); } function setConstitutionRegistry(address newRegistry) onlyOwner { require(constitutionRegistry != newRegistry); constitutionRegistry = ConstitutionRegistry(newRegistry); ConstitutionRegistryChanged(newRegistry); } function setCodeOfLawRegistry(address newRegistry) onlyOwner { require(codeOfLawRegistry != newRegistry); codeOfLawRegistry = CodeOfLawRegistry(newRegistry); CodeOfLawRegistryChanged(newRegistry); } function addNationAt(string name, address at, uint constitutionId, uint codeOfLawId) returns (uint nationId) { // Check that the constitution & codeOfLaw exists require(constitutionRegistry.exist(constitutionId)); require(codeOfLawRegistry.exist(codeOfLawId)); nationId = allNations.length++; allNations[nationId].at = at; allNations[nationId].name = name; allNations[nationId].timestamp = now; allNations[nationId].constitution = constitutionId; allNations[nationId].codeOfLaw = codeOfLawId; NewNation(nationId, at, name, msg.sender); } function vote(uint nationId, bool voteInSupport) returns (uint voteId) { // Check if nation exist require(allNations[nationId].at != address(0x0)); // Check if already voted require(!allNations[nationId].didVote[msg.sender]); allNations[nationId].didVote[msg.sender] = true; voteId = allNations[nationId].allVotes.length++; allNations[nationId].allVotes[voteId] = Vote({voter: msg.sender, inSupport: voteInSupport, timestamp: now}); allNations[nationId].numVotes++; NewVote(nationId, msg.sender, voteInSupport, voteId); } function getVote(uint nationId, uint voteId) constant returns (address voter, bool inSupport, uint timestamp) { voter = allNations[nationId].allVotes[voteId].voter; inSupport = allNations[nationId].allVotes[voteId].inSupport; timestamp = allNations[nationId].allVotes[voteId].timestamp; } }
Check that the constitution & codeOfLaw exists
function addNationAt(string name, address at, uint constitutionId, uint codeOfLawId) returns (uint nationId) { require(constitutionRegistry.exist(constitutionId)); require(codeOfLawRegistry.exist(codeOfLawId)); nationId = allNations.length++; allNations[nationId].at = at; allNations[nationId].name = name; allNations[nationId].timestamp = now; allNations[nationId].constitution = constitutionId; allNations[nationId].codeOfLaw = codeOfLawId; NewNation(nationId, at, name, msg.sender); }
5,532,721
/** *Submitted for verification at Etherscan.io on 2022-03-22 */ // SPDX-License-Identifier: MIT //created by [email protected] of Co-Labs LLC. www.co-labs.studio // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.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); } /** * @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 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 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); } } abstract contract Minters is Ownable { mapping (address => bool) private _minters; function setMinter(address _address) public onlyOwner { _minters[_address]=true; } function isMinter(address _address) public view returns (bool){ return _minters[_address]; } } /** * @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 ToonzToken is Context, IERC20, IERC20Metadata, Minters { 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, 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) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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) external virtual payable { require(isMinter(msg.sender) == true, "Address does not have access to mint."); _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 Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 {} }
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) external virtual payable { require(isMinter(msg.sender) == true, "Address does not have access to mint."); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); }
6,808,827
pragma solidity ^0.4.23; /** * @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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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&#39;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; } } /** * @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 OwnershipRenounced(address indexed previousOwner); 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 { _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 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 unpauseunpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ 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]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit 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) { return balances[_owner]; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ 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); emit 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&#39;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) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit 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, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit 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, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ 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, uint256 _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Frozenable Token * @dev Illegal address that can be frozened. */ contract FrozenableToken is PausableToken { mapping (address => bool) public frozenAccount; event FrozenFunds(address indexed to, bool frozen); modifier whenNotFrozen(address _who) { require(!frozenAccount[msg.sender] && !frozenAccount[_who]); _; } function freezeAccount(address _to, bool _freeze) public onlyOwner { require(_to != address(0)); frozenAccount[_to] = _freeze; emit FrozenFunds(_to, _freeze); } function transfer(address _to, uint256 _value) public whenNotFrozen(_to) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotFrozen(_to) whenNotFrozen(_from) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotFrozen(_spender) returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint256 _addedValue) public whenNotFrozen(_spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotFrozen(_spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title TokenDestructible: * @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f7d6a626c604f3d">[email&#160;protected]</a>π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable,FrozenableToken { constructor() public payable { } /** * @notice Terminate contract and refund to owner * @param _tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] _tokens) public onlyOwner { // Transfer tokens to owner for (uint256 i = 0; i < _tokens.length; i++) { ERC20Basic token = ERC20Basic(_tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } /** * @title WuKong Token */ contract WuKongChain is PausableToken, FrozenableToken, TokenDestructible { string public name = "WuKongChain"; string public symbol = "WKC"; uint256 public decimals = 4; uint256 INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); /** * @dev Initializes the total release */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = totalSupply_; emit Transfer(address(0), msg.sender, totalSupply_); } }
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&39;s allowance to 0 and set the desired value afterwards: _spender The address which will spend the funds. _value The amount of tokens to be spent./
function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
7,769,289
./full_match/137/0xFd055AB59A7aC52d22116d47F08fE3980C4A2F88/sources/Proxy.sol
fetches and sorts the reserves for a pair
function getReserve( address factory, address tokenA, address tokenB, bytes32 initCode ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, initCode)) .getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); }
3,763,329
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @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 OwnershipRenounced(address indexed previousOwner); 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 relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); 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; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ 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); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ 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 ); } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/IMonethaVoucher.sol interface IMonethaVoucher { /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256); /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers (vouchers) to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256); /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers (vouchers) * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256); /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external returns (uint256 amountVouchers, uint256 amountWei); /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external returns (uint256 amountVouchers); /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external payable; /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external returns(uint256 weis); /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external returns (bool); /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256); } // File: monetha-utility-contracts/contracts/Restricted.sol /** @title Restricted * Exposes onlyMonetha modifier */ contract Restricted is Ownable { //MonethaAddress set event event MonethaAddressSet( address _address, bool _isMonethaAddress ); mapping (address => bool) public isMonethaAddress; /** * Restrict methods in such way, that they can be invoked only by monethaAddress account. */ modifier onlyMonetha() { require(isMonethaAddress[msg.sender]); _; } /** * Allows owner to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); } } // File: contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/ownership/CanReclaimEther.sol contract CanReclaimEther is Ownable { event ReclaimEther(address indexed to, uint256 amount); /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { uint256 value = address(this).balance; owner.transfer(value); emit ReclaimEther(owner, value); } /** * @dev Transfer specified amount of Ether held by the contract to the address. * @param _to The address which will receive the Ether * @param _value The amount of Ether to transfer */ function reclaimEtherTo(address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _to.transfer(_value); emit ReclaimEther(_to, _value); } } // File: contracts/ownership/CanReclaimTokens.sol contract CanReclaimTokens is Ownable { using SafeERC20 for ERC20Basic; event ReclaimTokens(address indexed to, uint256 amount); /** * @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); emit ReclaimTokens(owner, balance); } /** * @dev Reclaim specified amount of ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract * @param _to The address which will receive the tokens * @param _value The amount of tokens to transfer */ function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _token.safeTransfer(_to, _value); emit ReclaimTokens(_to, _value); } } // File: contracts/MonethaVoucher.sol contract MonethaVoucher is IMonethaVoucher, Restricted, Pausable, IERC20, CanReclaimEther, CanReclaimTokens { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event DiscountApplied(address indexed user, uint256 releasedVouchers, uint256 amountWeiTransferred); event PaybackApplied(address indexed user, uint256 addedVouchers, uint256 amountWeiEquivalent); event VouchersBought(address indexed user, uint256 vouchersBought); event VouchersSold(address indexed user, uint256 vouchersSold, uint256 amountWeiTransferred); event VoucherMthRateUpdated(uint256 oldVoucherMthRate, uint256 newVoucherMthRate); event MthEthRateUpdated(uint256 oldMthEthRate, uint256 newMthEthRate); event VouchersAdded(address indexed user, uint256 vouchersAdded); event VoucherReleased(address indexed user, uint256 releasedVoucher); event PurchasedVouchersReleased(address indexed from, address indexed to, uint256 vouchers); /* Public variables of the token */ string constant public standard = "ERC20"; string constant public name = "Monetha Voucher"; string constant public symbol = "MTHV"; uint8 constant public decimals = 5; /* For calculating half year */ uint256 constant private DAY_IN_SECONDS = 86400; uint256 constant private YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS; uint256 constant private LEAP_YEAR_IN_SECONDS = 366 * DAY_IN_SECONDS; uint256 constant private YEAR_IN_SECONDS_AVG = (YEAR_IN_SECONDS * 3 + LEAP_YEAR_IN_SECONDS) / 4; uint256 constant private HALF_YEAR_IN_SECONDS_AVG = YEAR_IN_SECONDS_AVG / 2; uint256 constant public RATE_COEFFICIENT = 1000000000000000000; // 10^18 uint256 constant private RATE_COEFFICIENT2 = RATE_COEFFICIENT * RATE_COEFFICIENT; // RATE_COEFFICIENT^2 uint256 public voucherMthRate; // number of voucher units in 10^18 MTH units uint256 public mthEthRate; // number of mth units in 10^18 wei uint256 internal voucherMthEthRate; // number of vouchers units (= voucherMthRate * mthEthRate) in 10^36 wei ERC20Basic public mthToken; mapping(address => uint256) public purchased; // amount of vouchers purchased by other monetha contract uint256 public totalPurchased; // total amount of vouchers purchased by monetha mapping(uint16 => uint256) public totalDistributedIn; // аmount of vouchers distributed in specific half-year mapping(uint16 => mapping(address => uint256)) public distributed; // amount of vouchers distributed in specific half-year to specific user constructor(uint256 _voucherMthRate, uint256 _mthEthRate, ERC20Basic _mthToken) public { require(_voucherMthRate > 0, "voucherMthRate should be greater than 0"); require(_mthEthRate > 0, "mthEthRate should be greater than 0"); require(_mthToken != address(0), "must be valid contract"); voucherMthRate = _voucherMthRate; mthEthRate = _mthEthRate; mthToken = _mthToken; _updateVoucherMthEthRate(); } /** * @dev Total number of vouchers in existence = vouchers in shared pool + vouchers distributed + vouchers purchased */ function totalSupply() external view returns (uint256) { return _totalVouchersSupply(); } /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256) { return _vouchersInSharedPool(_currentHalfYear()); } /** * @dev Total number of vouchers distributed */ function totalDistributed() external view returns (uint256) { return _vouchersDistributed(_currentHalfYear()); } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) external view returns (uint256) { return _distributedTo(owner, _currentHalfYear()).add(purchased[owner]); } /** * @dev Function to check the amount of vouchers 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 vouchers still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { owner; spender; return 0; } /** * @dev Transfer voucher for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) external returns (bool) { to; value; revert(); } /** * @dev Approve the passed address to spend the specified amount of vouchers 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 vouchers to be spent. */ function approve(address spender, uint256 value) external returns (bool) { spender; value; revert(); } /** * @dev Transfer vouchers from one address to another * @param from address The address which you want to send vouchers from * @param to address The address which you want to transfer to * @param value uint256 the amount of vouchers to be transferred */ function transferFrom(address from, address to, uint256 value) external returns (bool) { from; to; value; revert(); } // Allows direct funds send by Monetha function () external onlyMonetha payable { } /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256) { return _vouchersToWei(_value); } /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256) { return _weiToVouchers(_value); } /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external onlyMonetha returns (uint256 amountVouchers, uint256 amountWei) { require(_for != address(0), "zero address is not allowed"); uint256 releasedVouchers = _releaseVouchers(_for, _vouchers); if (releasedVouchers == 0) { return (0,0); } uint256 amountToTransfer = _vouchersToWei(releasedVouchers); require(address(this).balance >= amountToTransfer, "insufficient funds"); _for.transfer(amountToTransfer); emit DiscountApplied(_for, releasedVouchers, amountToTransfer); return (releasedVouchers, amountToTransfer); } /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external onlyMonetha returns (uint256 amountVouchers) { amountVouchers = _weiToVouchers(_amountWei); require(_addVouchers(_for, amountVouchers), "vouchers must be added"); emit PaybackApplied(_for, amountVouchers, _amountWei); } /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external onlyMonetha payable { uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _vouchers, "insufficient vouchers present"); require(msg.value == _vouchersToWei(_vouchers), "insufficient funds"); _addPurchasedTo(msg.sender, _vouchers); emit VouchersBought(msg.sender, _vouchers); } /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external onlyMonetha returns(uint256 weis) { require(_vouchers <= purchased[msg.sender], "Insufficient vouchers"); _subPurchasedFrom(msg.sender, _vouchers); weis = _vouchersToWei(_vouchers); msg.sender.transfer(weis); emit VouchersSold(msg.sender, _vouchers, weis); } /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external onlyMonetha returns (bool) { require(_value <= purchased[msg.sender], "Insufficient Vouchers"); require(_to != address(0), "address should be valid"); _subPurchasedFrom(msg.sender, _value); _addVouchers(_to, _value); emit PurchasedVouchersReleased(msg.sender, _to, _value); return true; } /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256) { return purchased[owner]; } /** * @dev updates voucherMthRate. */ function updateVoucherMthRate(uint256 _voucherMthRate) external onlyMonetha { require(_voucherMthRate > 0, "should be greater than 0"); require(voucherMthRate != _voucherMthRate, "same as previous value"); voucherMthRate = _voucherMthRate; _updateVoucherMthEthRate(); emit VoucherMthRateUpdated(voucherMthRate, _voucherMthRate); } /** * @dev updates mthEthRate. */ function updateMthEthRate(uint256 _mthEthRate) external onlyMonetha { require(_mthEthRate > 0, "should be greater than 0"); require(mthEthRate != _mthEthRate, "same as previous value"); mthEthRate = _mthEthRate; _updateVoucherMthEthRate(); emit MthEthRateUpdated(mthEthRate, _mthEthRate); } function _addPurchasedTo(address _to, uint256 _value) internal { purchased[_to] = purchased[_to].add(_value); totalPurchased = totalPurchased.add(_value); } function _subPurchasedFrom(address _from, uint256 _value) internal { purchased[_from] = purchased[_from].sub(_value); totalPurchased = totalPurchased.sub(_value); } function _updateVoucherMthEthRate() internal { voucherMthEthRate = voucherMthRate.mul(mthEthRate); } /** * @dev Transfer vouchers from shared pool to address. May be called only by Monetha. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _addVouchers(address _to, uint256 _value) internal returns (bool) { require(_to != address(0), "zero address is not allowed"); uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _value, "must be less or equal than vouchers present in shared pool"); uint256 oldDist = totalDistributedIn[currentHalfYear]; totalDistributedIn[currentHalfYear] = oldDist.add(_value); uint256 oldBalance = distributed[currentHalfYear][_to]; distributed[currentHalfYear][_to] = oldBalance.add(_value); emit VouchersAdded(_to, _value); return true; } /** * @dev Transfer vouchers from address to shared pool * @param _from address The address which you want to send vouchers from * @param _value uint256 the amount of vouchers to be transferred * @return A uint256 specifying the amount of vouchers released to shared pool. */ function _releaseVouchers(address _from, uint256 _value) internal returns (uint256) { require(_from != address(0), "must be valid address"); uint16 currentHalfYear = _currentHalfYear(); uint256 released = 0; if (currentHalfYear > 0) { released = released.add(_releaseVouchers(_from, _value, currentHalfYear - 1)); _value = _value.sub(released); } released = released.add(_releaseVouchers(_from, _value, currentHalfYear)); emit VoucherReleased(_from, released); return released; } function _releaseVouchers(address _from, uint256 _value, uint16 _currentHalfYear) internal returns (uint256) { if (_value == 0) { return 0; } uint256 oldBalance = distributed[_currentHalfYear][_from]; uint256 subtracted = _value; if (oldBalance <= _value) { delete distributed[_currentHalfYear][_from]; subtracted = oldBalance; } else { distributed[_currentHalfYear][_from] = oldBalance.sub(_value); } uint256 oldDist = totalDistributedIn[_currentHalfYear]; if (oldDist == subtracted) { delete totalDistributedIn[_currentHalfYear]; } else { totalDistributedIn[_currentHalfYear] = oldDist.sub(subtracted); } return subtracted; } // converts vouchers to Ether (in wei) function _vouchersToWei(uint256 _value) internal view returns (uint256) { return _value.mul(RATE_COEFFICIENT2).div(voucherMthEthRate); } // converts Ether (in wei) to vouchers function _weiToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthEthRate).div(RATE_COEFFICIENT2); } // converts MTH tokens to vouchers function _mthToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthRate).div(RATE_COEFFICIENT); } // converts Ether (in wei) to MTH function _weiToMth(uint256 _value) internal view returns (uint256) { return _value.mul(mthEthRate).div(RATE_COEFFICIENT); } function _totalVouchersSupply() internal view returns (uint256) { return _mthToVouchers(mthToken.balanceOf(address(this))); } function _vouchersInSharedPool(uint16 _currentHalfYear) internal view returns (uint256) { return _totalVouchersSupply().sub(_vouchersDistributed(_currentHalfYear)).sub(totalPurchased); } function _vouchersDistributed(uint16 _currentHalfYear) internal view returns (uint256) { uint256 dist = totalDistributedIn[_currentHalfYear]; if (_currentHalfYear > 0) { // include previous half-year dist = dist.add(totalDistributedIn[_currentHalfYear - 1]); } return dist; } function _distributedTo(address _owner, uint16 _currentHalfYear) internal view returns (uint256) { uint256 balance = distributed[_currentHalfYear][_owner]; if (_currentHalfYear > 0) { // include previous half-year balance = balance.add(distributed[_currentHalfYear - 1][_owner]); } return balance; } function _currentHalfYear() internal view returns (uint16) { return uint16(now / HALF_YEAR_IN_SECONDS_AVG); } }
Function allows Monetha account to release the purchased vouchers to any address. The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise it will be returned to shared pool. May be called only by Monetha. _to address to release vouchers to. _value the amount of vouchers to release./
function releasePurchasedTo(address _to, uint256 _value) external onlyMonetha returns (bool) { require(_value <= purchased[msg.sender], "Insufficient Vouchers"); require(_to != address(0), "address should be valid"); _subPurchasedFrom(msg.sender, _value); _addVouchers(_to, _value); emit PurchasedVouchersReleased(msg.sender, _to, _value); return true; }
1,015,241
./full_match/1/0x73d6B1EF5227EA7f97426a9ADE2b9006eb88eE5D/sources/contracts/token/MRANDMRSWOJAK.sol
Returns the name of the token./
function name() public view returns (string memory) { return _name; }
2,991,235
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface IERC20 { // brief interface for erc20 token tx function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } library Address { // helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } } library SafeERC20 { // wrapper around erc20 token tx for non-standard contract - see openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol 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 _callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returnData) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returnData.length > 0) { // return data is optional require(abi.decode(returnData, (bool)), "SafeERC20: erc20 operation did not succeed"); } } } library SafeMath { // arithmetic wrapper for unit under/overflow check function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); 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); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } } contract ReentrancyGuard { // call wrapper for reentrancy check uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() internal { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } contract MSTX is ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; /*************** GLOBAL CONSTANTS ***************/ address public depositToken; // deposit token contract reference - default = wETH address public stakeToken; // stake token contract reference for guild voting shares address public constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // canonical ether token wrapper contract reference uint256 public proposalDeposit; // default = 10 deposit token uint256 public processingReward; // default = 0.1 - amount of deposit token to give to whoever processes a proposal uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public summoningTime; // needed to determine the current period bool private initialized; // internally tracks deployment under eip-1167 proxy pattern // HARD-CODED LIMITS uint256 constant MAX_GUILD_BOUND = 10**36; // maximum bound for guild member accounting uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // GUILD TOKEN DETAILS uint8 public constant decimals = 18; string public constant name = "MSTX"; string public constant symbol = "MSTX"; // ******************* // INTERNAL ACCOUNTING // ******************* address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xdeaf); address public constant TOTAL = address(0xdeed); uint256 public proposalCount; // total proposals submitted uint256 public totalShares; // total shares across all members uint256 public totalLoot; // total loot across all members uint256 public totalSupply; // total shares & loot across all members (total guild tokens) uint256 public totalGuildBankTokens; // total tokens with non-zero balance in guild bank mapping(uint256 => bytes) public actions; // proposalId => action data mapping(address => uint256) public balanceOf; // guild token balances mapping(address => mapping(address => uint256)) public allowance; // guild token (loot) allowances mapping(address => mapping(address => uint256)) private userTokenBalances; // userTokenBalances[userAddress][tokenAddress] address[] public approvedTokens; mapping(address => bool) public tokenWhitelist; uint256[] public proposalQueue; mapping(uint256 => Proposal) public proposals; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; // ************** // EVENT TRACKING // ************** event SubmitProposal(address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, uint8[9] flags, bytes data, uint256 proposalId, address indexed delegateKey, address indexed memberAddress); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event SponsorProposal(address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod); event SubmitVote(uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessActionProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessGuildKickProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWhitelistProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWithdrawalProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey); event Ragequit(address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn); event TokensCollected(address indexed token, uint256 amountToCollect); event Withdraw(address indexed memberAddress, address token, uint256 amount); event ConvertSharesToLoot(address indexed memberAddress, uint256 amount); event StakeTokenForShares(address indexed memberAddress, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); // guild token (loot) allowance tracking event Transfer(address indexed sender, address indexed recipient, uint256 amount); // guild token mint, burn & loot transfer tracking enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals & voting - defaults to member address unless updated uint8 exists; // always true (1) once a member has been created uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragekick) - transferable by guild token uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on & sponsoring proposals } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as target for alt. proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) address tributeToken; // tribute token contract reference address paymentToken; // payment token contract reference uint8[9] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 paymentRequested; // amount of tokens requested as payment uint256 tributeOffered; // amount of tokens offered as tribute uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal bytes32 details; // proposal details to add context for members mapping(address => Vote) votesByMember; // the votes on this proposal by each member } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "!delegate"); _; } function init( address _depositToken, address _stakeToken, address[] memory _summoner, uint256[] memory _summonerShares, uint256 _summonerDeposit, uint256 _proposalDeposit, uint256 _processingReward, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _dilutionBound ) external { require(!initialized, "initialized"); require(_depositToken != _stakeToken, "depositToken = stakeToken"); require(_summoner.length == _summonerShares.length, "summoner != summonerShares"); require(_proposalDeposit >= _processingReward, "_processingReward > _proposalDeposit"); for (uint256 i = 0; i < _summoner.length; i++) { growGuild(_summoner[i], _summonerShares[i], 0); } require(totalShares <= MAX_GUILD_BOUND, "guild maxed"); tokenWhitelist[_depositToken] = true; approvedTokens.push(_depositToken); if (_summonerDeposit > 0) { totalGuildBankTokens += 1; unsafeAddToBalance(GUILD, _depositToken, _summonerDeposit); } depositToken = _depositToken; stakeToken = _stakeToken; proposalDeposit = _proposalDeposit; processingReward = _processingReward; periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; dilutionBound = _dilutionBound; summoningTime = now; initialized = true; } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details ) external nonReentrant payable returns (uint256 proposalId) { require(sharesRequested.add(lootRequested) <= MAX_GUILD_BOUND, "guild maxed"); require(tokenWhitelist[tributeToken], "tributeToken != whitelist"); require(tokenWhitelist[paymentToken], "paymentToken != whitelist"); require(applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant unreservable"); require(members[applicant].jailed == 0, "applicant jailed"); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed"); } // collect tribute from proposer & store it in MSTX until the proposal is processed - if ether, wrap into wETH if (msg.value > 0) { require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance"); (bool success, ) = wETH.call{value: msg.value}(""); require(success, "!ethCall"); IERC20(wETH).safeTransfer(address(this), msg.value); } else { IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered); } unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[8] = 1; // standard _submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, ""); return proposalCount - 1; // return proposalId - contracts calling submit might want it } function submitActionProposal( // stages arbitrary function calls for member vote - based on Raid Guild 'Minion' address actionTo, // target account for action (e.g., address to receive ether, token, dao, etc.) uint256 actionTokenAmount, // helps check outbound guild bank token amount does not exceed internal balance / amount to update bank if successful uint256 actionValue, // ether value, if any, in call bytes32 details, // details tx staged for member execution - as external, extra care should be applied in diligencing action bytes calldata data // data for function call ) external returns (uint256 proposalId) { uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[6] = 1; // action _submitProposal(actionTo, 0, 0, actionValue, address(0), actionTokenAmount, address(0), details, flags, data); return proposalCount - 1; } function submitGuildKickProposal(address memberToKick, bytes32 details) external returns (uint256 proposalId) { Member memory member = members[memberToKick]; require(member.shares > 0 || member.loot > 0, "!share||loot"); require(members[memberToKick].jailed == 0, "jailed"); uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[5] = 1; // guildkick _submitProposal(memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags, ""); return proposalCount - 1; } function submitWhitelistProposal(address tokenToWhitelist, bytes32 details) external returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "!token"); require(tokenToWhitelist != stakeToken, "tokenToWhitelist = stakeToken"); require(!tokenWhitelist[tokenToWhitelist], "whitelisted"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "whitelist maxed"); uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[4] = 1; // whitelist _submitProposal(address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags, ""); return proposalCount - 1; } function submitWithdrawalProposal(address withdrawalTo, bytes32 details) external returns (uint256 proposalId) { uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard] flags[7] = 1; // withdrawal _submitProposal(withdrawalTo, 0, 0, 0, address(0), 0, address(0), details, flags, ""); return proposalCount - 1; } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, uint8[9] memory flags, bytes memory data ) internal { Proposal memory proposal = Proposal({ applicant : applicant, proposer : msg.sender, sponsor : address(0), tributeToken : tributeToken, paymentToken : paymentToken, flags : flags, sharesRequested : sharesRequested, lootRequested : lootRequested, paymentRequested : paymentRequested, tributeOffered : tributeOffered, startingPeriod : 0, yesVotes : 0, noVotes : 0, maxTotalSharesAndLootAtYesVote : 0, details : details }); if (proposal.flags[6] == 1) { actions[proposalCount] = data; } proposals[proposalCount] = proposal; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, data, proposalCount, msg.sender, memberAddressByDelegateKey[msg.sender]); proposalCount += 1; } function sponsorProposal(uint256 proposalId) external nonReentrant onlyDelegate { // collect proposal deposit from sponsor & store it in MSTX until the proposal is processed IERC20(depositToken).safeTransferFrom(msg.sender, address(this), proposalDeposit); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; require(proposal.proposer != address(0), "!proposed"); require(proposal.flags[0] == 0, "sponsored"); require(proposal.flags[3] == 0, "cancelled"); require(members[proposal.applicant].jailed == 0, "applicant jailed"); if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed"); } // whitelist proposal if (proposal.flags[4] == 1) { require(!tokenWhitelist[address(proposal.tributeToken)], "whitelisted"); require(!proposedToWhitelist[address(proposal.tributeToken)], "whitelist proposed"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "whitelist maxed"); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.flags[5] == 1) { require(!proposedToKick[proposal.applicant], "kick proposed"); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]].startingPeriod ) + 1; proposal.startingPeriod = startingPeriod; proposal.sponsor = memberAddressByDelegateKey[msg.sender]; proposal.flags[0] = 1; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal(msg.sender, proposal.sponsor, proposalId, proposalQueue.length - 1, startingPeriod); } // NOTE: In MSTX, proposalIndex != proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) external nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "!proposed"); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(uintVote < 3, ">2"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "pending"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "voted"); require(vote == Vote.Yes || vote == Vote.No, "!Yes||No"); proposal.votesByMember[memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes += member.shares; // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalSupply > proposal.maxTotalSharesAndLootAtYesVote) { proposal.maxTotalSharesAndLootAtYesVote = totalSupply; } } else if (vote == Vote.No) { proposal.noVotes += member.shares; } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set until it's been sponsored but proposal is created on submission emit SubmitVote(proposalId, proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) external nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[8] == 1, "!standard"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares & loot exceeds the limit if (totalSupply.add(proposal.sharesRequested).add(proposal.lootRequested) > MAX_GUILD_BOUND) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = 1; // didPass growGuild(proposal.applicant, proposal.sharesRequested, proposal.lootRequested); // if the proposal tribute is the first token of its kind to make it into the guild bank, increment total guild bank tokens if (userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0) { totalGuildBankTokens += 1; } unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processActionProposal(uint256 proposalIndex) external nonReentrant returns (bool, bytes memory) { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; bytes storage action = actions[proposalId]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[6] == 1, "!action"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if it is requesting more accounted tokens than the available guild bank balance if (tokenWhitelist[proposal.applicant] && proposal.paymentRequested > userTokenBalances[GUILD][proposal.applicant]) { didPass = false; } // Make the proposal fail if it is requesting more ether than the available local balance if (proposal.tributeOffered > address(this).balance) { didPass = false; } if (didPass) { proposal.flags[2] = 1; // didPass (bool success, bytes memory returnData) = proposal.applicant.call{value: proposal.tributeOffered}(action); if (tokenWhitelist[proposal.applicant]) { unsafeSubtractFromBalance(GUILD, proposal.applicant, proposal.paymentRequested); // if the action proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.applicant] == 0 && proposal.paymentRequested > 0) {totalGuildBankTokens -= 1;} } return (success, returnData); } _returnDeposit(proposal.sponsor); emit ProcessActionProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) external nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[5] == 1, "!kick"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = 1; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot.add(member.shares); totalShares = totalShares.sub(member.shares); totalLoot = totalLoot.add(member.shares); member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) external { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[4] == 1, "!whitelist"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { proposal.flags[2] = 1; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processWithdrawalProposal(uint256 proposalIndex) external nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[7] == 1, "!withdrawal"); proposal.flags[1] = 1; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = 1; // didPass for (uint256 i = 0; i < approvedTokens.length; i++) { // deliberately not using safemath here to keep overflows from preventing the function execution (which would break withdrawal) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways uint256 withdrawalAmount = userTokenBalances[GUILD][approvedTokens[i]]; userTokenBalances[GUILD][approvedTokens[i]] -= withdrawalAmount; userTokenBalances[proposal.applicant][approvedTokens[i]] += withdrawalAmount; } totalGuildBankTokens -= approvedTokens.length; } _returnDeposit(proposal.sponsor); emit ProcessWithdrawalProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal view returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; if (proposal.yesVotes > proposal.noVotes) { didPass = true; } // Make the proposal fail if the dilutionBound is exceeded if ((totalSupply.mul(dilutionBound)) < proposal.maxTotalSharesAndLootAtYesVote) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require(proposalIndex < proposalQueue.length, "!proposal"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "!ready"); require(proposal.flags[1] == 0, "processed"); require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex - 1]].flags[1] == 1, "prior !processed"); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer(ESCROW, msg.sender, depositToken, processingReward); unsafeInternalTransfer(ESCROW, sponsor, depositToken, proposalDeposit - processingReward); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) external nonReentrant { require(members[msg.sender].exists == 1, "!member"); _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit(address memberAddress, uint256 sharesToBurn, uint256 lootToBurn) internal { uint256 initialTotalSharesAndLoot = totalSupply; Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "!shares"); require(member.loot >= lootToBurn, "!loot"); require(canRagequit(member.highestIndexYesVote), "!ragequit until highest index proposal member voted YES processes"); uint256 sharesAndLootToBurn = sharesToBurn.add(lootToBurn); // burn guild token, shares & loot balanceOf[memberAddress] = balanceOf[memberAddress].sub(sharesAndLootToBurn); member.shares = member.shares.sub(sharesToBurn); member.loot = member.loot.sub(lootToBurn); totalShares = totalShares.sub(sharesToBurn); totalLoot = totalLoot.sub(lootToBurn); totalSupply = totalShares.add(totalLoot); for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit; } } emit Ragequit(memberAddress, sharesToBurn, lootToBurn); emit Transfer(memberAddress, address(0), sharesAndLootToBurn); } function ragekick(address memberToKick) external nonReentrant onlyDelegate { Member storage member = members[memberToKick]; require(member.jailed != 0, "!jailed"); require(member.loot > 0, "!loot"); // note - should be impossible for jailed member to have shares require(canRagequit(member.highestIndexYesVote), "!ragequit until highest index proposal member voted YES processes"); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address token, uint256 amount) external nonReentrant { _withdrawBalance(token, amount); } function withdrawBalances(address[] calldata tokens, uint256[] calldata amounts, bool max) external nonReentrant { require(tokens.length == amounts.length, "tokens != amounts"); for (uint256 i=0; i < tokens.length; i++) { uint256 withdrawAmount = amounts[i]; if (max) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][tokens[i]]; } _withdrawBalance(tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require(userTokenBalances[msg.sender][token] >= amount, "!balance"); IERC20(token).safeTransfer(msg.sender, amount); unsafeSubtractFromBalance(msg.sender, token, amount); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) external nonReentrant onlyDelegate { uint256 amountToCollect = IERC20(token).balanceOf(address(this)).sub(userTokenBalances[TOTAL][token]); // only collect if 1) there are tokens to collect & 2) token is whitelisted require(amountToCollect > 0, "!amount"); require(tokenWhitelist[token], "!whitelisted"); if (userTokenBalances[GUILD][token] == 0 && totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT) {totalGuildBankTokens += 1;} unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender = proposal.proposer function cancelProposal(uint256 proposalId) external nonReentrant { Proposal storage proposal = proposals[proposalId]; require(proposal.flags[0] == 0, "sponsored"); require(proposal.flags[3] == 0, "cancelled"); require(msg.sender == proposal.proposer, "!proposer"); proposal.flags[3] = 1; // cancelled unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) external { require(members[msg.sender].shares > 0, "!shareholder"); require(newDelegateKey != address(0), "newDelegateKey = 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(members[newDelegateKey].exists == 0, "!overwrite members"); require(members[memberAddressByDelegateKey[newDelegateKey]].exists == 0, "!overwrite keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "!proposal"); return proposals[proposalQueue[highestIndexYesVote]].flags[1] == 1; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength); } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return now.sub(summoningTime).div(periodDuration); } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) external view returns (Vote) { require(members[memberAddress].exists == 1, "!member"); require(proposalIndex < proposalQueue.length, "!proposed"); return proposals[proposalQueue[proposalIndex]].votesByMember[memberAddress]; } function getProposalFlags(uint256 proposalId) external view returns (uint8[9] memory) { return proposals[proposalId].flags; } function getProposalQueueLength() external view returns (uint256) { return proposalQueue.length; } function getTokenCount() external view returns (uint256) { return approvedTokens.length; } function getUserTokenBalance(address user, address token) external view returns (uint256) { return userTokenBalances[user][token]; } /*************** HELPER FUNCTIONS ***************/ receive() external payable {} function fairShare(uint256 balance, uint256 shares, uint256 totalSharesAndLoot) internal pure returns (uint256) { require(totalSharesAndLoot != 0); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / totalSharesAndLoot; } return (balance / totalSharesAndLoot) * shares; } function growGuild(address account, uint256 shares, uint256 loot) internal { // if the account is already a member, add to their existing shares & loot if (members[account].exists == 1) { members[account].shares = members[account].shares.add(shares); members[account].loot = members[account].loot.add(loot); // if the account is a new member, create a new record for them } else { // if new member is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[account]].exists == 1) { address memberToOverride = memberAddressByDelegateKey[account]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } members[account] = Member({ delegateKey : account, exists : 1, // 'true' shares : shares, loot : loot.add(members[account].loot), // take into account loot from pre-membership transfers highestIndexYesVote : 0, jailed : 0 }); memberAddressByDelegateKey[account] = account; } uint256 sharesAndLoot = shares.add(loot); // mint new guild token, update total shares & loot balanceOf[account] = balanceOf[account].add(sharesAndLoot); totalShares = totalShares.add(shares); totalLoot = totalLoot.add(loot); totalSupply = totalShares.add(totalLoot); emit Transfer(address(0), account, sharesAndLoot); } function unsafeAddToBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } function unsafeInternalTransfer(address from, address to, address token, uint256 amount) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function unsafeSubtractFromBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } /******************** GUILD TOKEN FUNCTIONS ********************/ function approve(address spender, uint256 amount) external returns (bool) { require(amount == 0 || allowance[msg.sender][spender] == 0); allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function convertSharesToLoot(uint256 sharesToLoot) external nonReentrant { members[msg.sender].shares = members[msg.sender].shares.sub(sharesToLoot); members[msg.sender].loot = members[msg.sender].loot.add(sharesToLoot); totalShares = totalShares.sub(sharesToLoot); totalLoot = totalLoot.add(sharesToLoot); emit ConvertSharesToLoot(msg.sender, sharesToLoot); } function stakeTokenForShares(uint256 amount) external nonReentrant { IERC20(stakeToken).safeTransferFrom(msg.sender, address(this), amount); // deposit stake token & claim shares (1:1) growGuild(msg.sender, amount, 0); require(totalSupply <= MAX_GUILD_BOUND, "guild maxed"); emit StakeTokenForShares(msg.sender, amount); } function transfer(address recipient, uint256 lootToTransfer) external returns (bool) { members[msg.sender].loot = members[msg.sender].loot.sub(lootToTransfer); members[recipient].loot = members[recipient].loot.add(lootToTransfer); balanceOf[msg.sender] = balanceOf[msg.sender].sub(lootToTransfer); balanceOf[recipient] = balanceOf[recipient].add(lootToTransfer); emit Transfer(msg.sender, recipient, lootToTransfer); return true; } function transferFrom(address sender, address recipient, uint256 lootToTransfer) external returns (bool) { allowance[sender][msg.sender] = allowance[sender][msg.sender].sub(lootToTransfer); members[sender].loot = members[sender].loot.sub(lootToTransfer); members[recipient].loot = members[recipient].loot.add(lootToTransfer); balanceOf[sender] = balanceOf[sender].sub(lootToTransfer); balanceOf[recipient] = balanceOf[recipient].add(lootToTransfer); emit Transfer(sender, recipient, lootToTransfer); return true; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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. */ contract CloneFactory { // MSTX implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 function createClone(address payable target) internal returns (address payable result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } } contract MSTXSummoner is CloneFactory { address payable public immutable template; constructor(address payable _template) public { template = _template; } event SummonMSTX(address indexed mstx, address depositToken, address stakeToken, address[] summoner, uint256[] summonerShares, uint256 summoningDeposit, uint256 proposalDeposit, uint256 processingReward, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 dilutionBound, uint256 summoningTime); function summonMSTX( address _depositToken, address _stakeToken, address[] memory _summoner, uint256[] memory _summonerShares, uint256 _summonerDeposit, uint256 _proposalDeposit, uint256 _processingReward, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _dilutionBound ) external returns (address) { MSTX mstx = MSTX(createClone(template)); mstx.init( _depositToken, _stakeToken, _summoner, _summonerShares, _summonerDeposit, _proposalDeposit, _processingReward, _periodDuration, _votingPeriodLength, _gracePeriodLength, _dilutionBound ); require(IERC20(_depositToken).transferFrom(msg.sender, address(mstx), _summonerDeposit), "!transfer"); // transfer summoner deposit to new MSTX emit SummonMSTX(address(mstx), _depositToken, _stakeToken, _summoner, _summonerShares, _summonerDeposit, _proposalDeposit, _processingReward, _periodDuration, _votingPeriodLength, _gracePeriodLength, _dilutionBound, now); return address(mstx); } }
can only ragequit if the latest proposal you voted YES on has been processed
function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "!proposal"); return proposals[proposalQueue[highestIndexYesVote]].flags[1] == 1; }
1,235,868
./full_match/4/0x0A87021D82453AB0B18a375aFfdB8C689e05A182/sources/sirtoken3.sol
swaps tokens -> eth return uint256 difference from previous contract balance/
function swapTokens2Eth(uint256 amount_) private returns (uint256) { uint256 initialBalance = address(this).balance; address[] memory path = new address[](2); path[0] = address(this); path[1] = Addr[Key.WETH]; _approve(address(this), Addr[Key.ROUTER], amount_); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( amount_, 0, path, address(this), block.timestamp ); return address(this).balance.sub(initialBalance); }
12,424,995
pragma solidity ^0.5.4; import "../Dependencies/Members.sol"; import "../Dependencies/VerifierInterface.sol"; import "../Dependencies/MiMCInterface.sol"; import "../Shared/Owned.sol"; import "../Shared/Operated.sol"; contract FluxVote is Owned { // should be operated using Members for Members.Data; MiMCInterface public mimc; // not public VerifierInterface public verifier; // not public Members.Data public members; // not public struct Vote { bytes message; uint256 timestamp; } mapping(bytes32 => Vote) public votes; bytes32[] public votesIndex; string description; // uint256 startDate; // uint256 endDate; bool public open; uint public initiated; uint public closed; // should be end?? event Voted(bytes32 key); // Must be copied here to be added to the ABI event MemberAdded(address indexed memberAddress, string name, uint totalAfter); event MemberRemoved(address indexed memberAddress, string name, uint totalAfter); event MemberNameUpdated(address indexed memberAddress, string oldName, string newName); constructor () public { initOwned(msg.sender); members.init(); open = true; initiated = now; closed = 0; } // Owner functions function setMiMC(address _mimc) public onlyOwner { mimc = MiMCInterface(_mimc); } function setVerifier(address _verifier) public onlyOwner { verifier = VerifierInterface(_verifier); } // Member functions function addMember(address _address, string memory _name) public onlyOwner { members.add(_address, _name); } function removeMember(address _address) public onlyOwner { members.remove(_address); } function setMemberName(string memory memberName) public { members.setName(msg.sender, memberName); } function numberOfMembers() public view returns (uint) { return members.length(); } function getMembers() public view returns (address[] memory) { return members.index; } function getMemberData(address _address) public view returns (bool _exists, uint _index, string memory _name) { Members.Member memory member = members.entries[_address]; return (member.exists, member.index, member.name); } function getMemberByIndex(uint _index) public view returns (address _member) { return members.index[_index]; } // Voting functions function voteKey(bytes memory _message) internal pure returns (bytes32) { // return sha256( _message); // salted? return keccak256(abi.encodePacked( _message)); // changed to MiMC? } function vote (/* uint256 ballotId,*/ bytes memory message) public { require(open); // add message to registry bytes32 key = voteKey(message); votes[key] = Vote(message, now); votesIndex.push(key); // not sure if this is correct emit Voted(key); } function votesIndexLength() public view returns (uint) { return votesIndex.length; } // is this just the same as voting? should be for greater annomity function changeKey (/* uint256 ballotId,*/ bytes memory message) public { } function verifyVote (string memory zkproof, bytes32 key) public { } function submitResults (string memory zkproof ,/* uint256 ballotId,*/ bool result) public onlyOwner { // should be operators } }
is this just the same as voting? should be for greater annomity
function changeKey (/* uint256 ballotId,*/ bytes memory message) public { }
12,733,592
pragma solidity ^0.4.25; /******************************************************************************* * * Copyright (c) 2019 Decentralization Authority MDAO. * Released under the MIT License. * * Minado - Crypto Token Mining & Forging Community * * Minado has been optimized for mining ERC918-compatible tokens via * the InfinityPool; a public storage of mineable ERC-20 tokens. * * Learn more below: * * Official : https://minado.network * Ethereum : https://eips.ethereum.org/EIPS/eip-918 * Github : https://github.com/ethereum/EIPs/pull/918 * Reddit : https://www.reddit.com/r/Tokenmining * * Version 19.7.18 * * Web : https://d14na.org * Email : support@d14na.org */ /******************************************************************************* * * SafeMath */ 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; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ contract ECRecovery { function recover(bytes32 hash, bytes sig) public pure returns (address); } /******************************************************************************* * * 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); } } /******************************************************************************* * * Zer0netDb Interface */ contract Zer0netDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * 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); } /******************************************************************************* * * InfinityPool Interface */ contract InfinityPoolInterface { function transfer(address _token, address _to, uint _tokens) external returns (bool success); } /******************************************************************************* * * InfinityWell Interface */ contract InfinityWellInterface { function forgeStones(address _owner, uint _tokens) external returns (bool success); function destroyStones(address _owner, uint _tokens) external returns (bool success); function transferERC20(address _token, address _to, uint _tokens) external returns (bool success); function transferERC721(address _token, address _to, uint256 _tokenId) external returns (bool success); } /******************************************************************************* * * Staek(house) Factory Interface */ contract StaekFactoryInterface { function balanceOf(bytes32 _staekhouseId) public view returns (uint balance); function balanceOf(bytes32 _staekhouseId, address _owner) public view returns (uint balance); function getStaekhouse(bytes32 _staekhouseId, address _staeker) external view returns (address factory, address token, address owner, uint ownerLockTime, uint providerLockTime, uint debtLimit, uint lockInterval, uint balance); } /******************************************************************************* * * @notice Minado - Token Mining Contract * * @dev This is a multi-token mining contract, which manages the proof-of-work * verifications before authorizing the movement of tokens from the * InfinityPool and InfinityWell. */ contract Minado is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /** * Set Namespace * * Provides a "unique" name for generating "unique" data identifiers, * most commonly used as database "key-value" keys. * * NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL * Zer0netDb keys; in order to prevent ANY accidental or * malicious SQL-injection vulnerabilities / attacks. */ string private _namespace = 'minado'; /** * Large Target * * A big number used for difficulty targeting. * * NOTE: Bitcoin uses `2**224`. */ uint private _MAXIMUM_TARGET = 2**234; /** * Minimum Targets * * Minimum number used for difficulty targeting. */ uint private _MINIMUM_TARGET = 2**16; /** * Set basis-point multiplier. * * NOTE: Used for (integer-based) fractional calculations. */ uint private _BP_MUL = 10000; /* Set InfinityStone decimals. */ uint private _STONE_DECIMALS = 18; /* Set single InfinityStone. */ uint private _SINGLE_STONE = 1 * 10**_STONE_DECIMALS; /** * (Ethereum) Blocks Per Forge * * NOTE: Ethereum blocks take approx 15 seconds each. * 1,000 blocks takes approx 4 hours. */ uint private _BLOCKS_PER_STONE_FORGE = 1000; /** * (Ethereum) Blocks Per Generation * * NOTE: We mirror the Bitcoin POW mining algorithm. * We want miners to spend 10 minutes to mine each 'block'. * (about 40 Ethereum blocks for every 1 Bitcoin block) */ uint BLOCKS_PER_GENERATION = 40; // Mainnet & Ropsten // uint BLOCKS_PER_GENERATION = 120; // Kovan /** * (Mint) Generations Per Re-adjustment * * By default, we automatically trigger a difficulty adjustment * after 144 generations / mints (approx 24 hours). * * Frequent adjustments are especially important with low-liquidity * tokens, which are more susceptible to mining manipulation. * * For additional control, token providers retain the ability to trigger * a difficulty re-calculation at any time. * * NOTE: Bitcoin re-adjusts its difficulty every 2,016 generations, * which occurs approx. every 14 days. */ uint private _DEFAULT_GENERATIONS_PER_ADJUSTMENT = 144; // approx. 24hrs event Claim( address owner, address token, uint amount, address collectible, uint collectibleId ); event Excavate( address indexed token, address indexed miner, uint mintAmount, uint epochCount, bytes32 newChallenge ); event Mint( address indexed from, uint rewardAmount, uint epochCount, bytes32 newChallenge ); event ReCalculate( address token, uint newDifficulty ); event Solution( address indexed token, address indexed miner, uint difficulty, uint nonce, bytes32 challenge, bytes32 newChallenge ); /* Constructor. */ constructor() public { /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); // _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN // _zer0netDb = Zer0netDbInterface(0x3e246C5038287DEeC6082B95b5741c147A3f49b3); // KOVAN /* Initialize (aname) hash. */ bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace)); /* Set predecessor address. */ _predecessor = _zer0netDb.getAddress(hash); /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = Minado(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true); _; // function code is inserted here } /** * @dev Only allow access to "registered" authorized user/contract. */ modifier onlyTokenProvider( address _token ) { /* Validate authorized token manager. */ require(_zer0netDb.getBool(keccak256(abi.encodePacked( _namespace, '.', msg.sender, '.has.auth.for.', _token ))) == true); _; // function code is inserted here } /** * THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER */ function () public payable { /* Cancel this transaction. */ revert('Oops! Direct payments are NOT permitted here.'); } /*************************************************************************** * * ACTIONS * */ /** * Initialize Token */ function init( address _token, address _provider ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(hash, block.number); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _DEFAULT_GENERATIONS_PER_ADJUSTMENT); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Set mining target. */ // NOTE: This is the default difficulty of 1. _setMiningTarget( _token, _MAXIMUM_TARGET ); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, true); return true; } /** * Mint */ function mint( address _token, bytes32 _digest, uint _nonce ) public returns (bool success) { /* Retrieve the current challenge. */ uint challenge = getChallenge(_token); /* Get mint digest. */ bytes32 digest = getMintDigest( challenge, msg.sender, _nonce ); /* The challenge digest must match the expected. */ if (digest != _digest) { revert('Oops! That solution is NOT valid.'); } /* The digest must be smaller than the target. */ if (uint(digest) > getTarget(_token)) { revert('Oops! That solution is NOT valid.'); } /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', digest, '.solutions' )); /* Retrieve value from Zer0net Db. */ uint solution = _zer0netDb.getUint(hash); /* Validate solution. */ if (solution != 0x0) { revert('Oops! That solution is a DUPLICATE.'); } /* Save this digest to 'solved' solutions. */ _zer0netDb.setUint(hash, uint(digest)); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ uint generation = _zer0netDb.getUint(hash); /* Increment the generation. */ generation = generation.add(1); /* Increment the generation count by 1. */ _zer0netDb.setUint(hash, generation); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(hash); // every so often, readjust difficulty. Dont readjust when deploying if (generation % genPerAdjustment == 0) { _reAdjustDifficulty(_token); } /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /** * Make the latest ethereum block hash a part of the next challenge * for PoW to prevent pre-mining future blocks. Do this last, * since this is a protection mechanism in the mint() function. */ _zer0netDb.setBytes( hash, _bytes32ToBytes(blockhash(block.number - 1)) ); /* Retrieve mining reward. */ // FIXME Add support for percentage reward. uint rewardAmount = getMintFixed(_token); /* Transfer (token) reward to minter. */ _infinityPool().transfer( _token, msg.sender, rewardAmount ); /* Emit log info. */ emit Mint( msg.sender, rewardAmount, generation, blockhash(block.number - 1) // next target ); /* Return success. */ return true; } /** * Test Mint Solution */ function testMint( bytes32 _digest, uint _challenge, address _minter, uint _nonce, uint _target ) public pure returns (bool success) { /* Retrieve digest. */ bytes32 digest = getMintDigest( _challenge, _minter, _nonce ); /* Validate digest. */ // NOTE: Cast type to 256-bit integer if (uint(digest) > _target) { /* Set flag. */ success = false; } else { /* Verify success. */ success = (digest == _digest); } } /** * Re-calculate Difficulty * * Token owner(s) can "manually" trigger the re-calculation of their token, * based on the parameters that have been set. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function reCalculateDifficulty( address _token ) external onlyTokenProvider(_token) returns (bool success) { /* Re-calculate difficulty. */ return _reAdjustDifficulty(_token); } /** * Re-adjust Difficulty * * Re-adjust the target by 5 percent. * (source: https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F) * * NOTE: Assume 240 ethereum blocks per hour (approx. 15/sec) * * NOTE: As of 2017 the bitcoin difficulty was up to 17 zeroes, * it was only 8 in the early days. */ function _reAdjustDifficulty( address _token ) private returns (bool success) { /* Set hash. */ bytes32 lastAdjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.last.adjustment' )); /* Retrieve value from Zer0net Db. */ uint lastAdjustment = _zer0netDb.getUint(lastAdjustmentHash); /* Retrieve value from Zer0net Db. */ uint blocksSinceLastAdjustment = block.number - lastAdjustment; /* Set hash. */ bytes32 adjustmentHash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ uint genPerAdjustment = _zer0netDb.getUint(adjustmentHash); /* Calculate number of expected blocks per adjustment. */ uint expectedBlocksPerAdjustment = genPerAdjustment.mul(BLOCKS_PER_GENERATION); /* Retrieve mining target. */ uint miningTarget = getTarget(_token); /* Validate the number of blocks passed; if there were less eth blocks * passed in time than expected, then miners are excavating too quickly. */ if (blocksSinceLastAdjustment < expectedBlocksPerAdjustment) { // NOTE: This number will be an integer greater than 10000. uint excess_block_pct = expectedBlocksPerAdjustment.mul(10000) .div(blocksSinceLastAdjustment); /** * Excess Block Percentage Extra * * For example: * If there were 5% more blocks mined than expected, then this is 500. * If there were 25% more blocks mined than expected, then this is 2500. */ uint excess_block_pct_extra = excess_block_pct.sub(10000); /* Set a maximum difficulty INCREASE of 50%. */ // NOTE: By default, this is within a 24hr period. if (excess_block_pct_extra > 5000) { excess_block_pct_extra = 5000; } /** * Reset the Mining Target * * Calculate the difficulty difference, then SUBTRACT * that value from the current difficulty. */ miningTarget = miningTarget.sub( /* Calculate difficulty difference. */ miningTarget .mul(excess_block_pct_extra) .div(10000) ); } else { // NOTE: This number will be an integer greater than 10000. uint shortage_block_pct = blocksSinceLastAdjustment.mul(10000) .div(expectedBlocksPerAdjustment); /** * Shortage Block Percentage Extra * * For example: * If it took 5% longer to mine than expected, then this is 500. * If it took 25% longer to mine than expected, then this is 2500. */ uint shortage_block_pct_extra = shortage_block_pct.sub(10000); // NOTE: There is NO limit on the amount of difficulty DECREASE. /** * Reset the Mining Target * * Calculate the difficulty difference, then ADD * that value to the current difficulty. */ miningTarget = miningTarget.add( miningTarget .mul(shortage_block_pct_extra) .div(10000) ); } /* Set current adjustment time in Zer0net Db. */ _zer0netDb.setUint(lastAdjustmentHash, block.number); /* Validate TOO SMALL mining target. */ // NOTE: This is very difficult to guess. if (miningTarget < _MINIMUM_TARGET) { miningTarget = _MINIMUM_TARGET; } /* Validate TOO LARGE mining target. */ // NOTE: This is very easy to guess. if (miningTarget > _MAXIMUM_TARGET) { miningTarget = _MAXIMUM_TARGET; } /* Set mining target. */ _setMiningTarget( _token, miningTarget ); /* Return success. */ return true; } /*************************************************************************** * * GETTERS * */ /** * Get Starting Block * * Starting Blocks * --------------- * * First blocks honoring the start of Miss Piggy's celebration year: * - Mainnet : 7,175,716 * - Ropsten : 4,956,268 * - Kovan : 10,283,438 * * NOTE: Pulls value from db `minado.starting.block` using the * respective networks. */ function getStartingBlock() public view returns (uint startingBlock) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.starting.block' )); /* Retrieve value from Zer0net Db. */ startingBlock = _zer0netDb.getUint(hash); } /** * Get minter's mintng address. */ function getMinter() external view returns (address minter) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.minter' )); /* Retrieve value from Zer0net Db. */ minter = _zer0netDb.getAddress(hash); } /** * Get generation details. */ function getGeneration( address _token ) external view returns ( uint generation, uint cycle ) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generation' )); /* Retrieve value from Zer0net Db. */ generation = _zer0netDb.getUint(hash); /* Set hash. */ hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Retrieve value from Zer0net Db. */ cycle = _zer0netDb.getUint(hash); } /** * Get Minting FIXED amount */ function getMintFixed( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get Minting PERCENTAGE amount */ function getMintPct( address _token ) public view returns (uint amount) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Retrieve value from Zer0net Db. */ amount = _zer0netDb.getUint(hash); } /** * Get (Mining) Challenge * * This is an integer representation of a recent ethereum block hash, * used to prevent pre-mining future blocks. */ function getChallenge( address _token ) public view returns (uint challenge) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.challenge' )); /* Retrieve value from Zer0net Db. */ // NOTE: Convert from bytes to integer. challenge = uint(_bytesToBytes32( _zer0netDb.getBytes(hash) )); } /** * Get (Mining) Difficulty * * The number of zeroes the digest of the PoW solution requires. * (auto adjusts) */ function getDifficulty( address _token ) public view returns (uint difficulty) { /* Caclulate difficulty. */ difficulty = _MAXIMUM_TARGET.div(getTarget(_token)); } /** * Get (Mining) Target */ function getTarget( address _token ) public view returns (uint target) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Retrieve value from Zer0net Db. */ target = _zer0netDb.getUint(hash); } /** * Get Mint Digest * * The PoW must contain work that includes a recent * ethereum block hash (challenge hash) and the * msg.sender's address to prevent MITM attacks */ function getMintDigest( uint _challenge, address _minter, uint _nonce ) public pure returns (bytes32 digest) { /* Calculate digest. */ digest = keccak256(abi.encodePacked( _challenge, _minter, _nonce )); } /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /*************************************************************************** * * SETTERS * */ /** * Set Generations Per (Difficulty) Adjustment * * Token owner(s) can adjust the number of generations * per difficulty re-calculation. * * NOTE: This will help deter malicious miners from gaming the difficulty * parameter, to the detriment of the token's community. */ function setGenPerAdjustment( address _token, uint _numBlocks ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.generations.per.adjustment' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _numBlocks); /* Return success. */ return true; } /** * Set (Fixed) Mint Amount */ function setMintFixed( address _token, uint _amount ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.fixed' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _amount); /* Return success. */ return true; } /** * Set (Dynamic) Mint Percentage */ function setMintPct( address _token, uint _pct ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.mint.pct' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _pct); /* Return success. */ return true; } /** * Set Token Parent(s) * * Enables the use of merged mining by specifying (parent) tokens * that offer an acceptibly HIGH difficulty for the child's own * mining challenge. * * Parents are saved in priority levels: * 1 - Most significant parent * 2 - 2nd most significant parent * ... * # - Least significant parent */ function setTokenParents( address _token, address[] _parents ) external onlyTokenProvider(_token) returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.parents' )); // FIXME How should we store a dynamic amount of parents? // Packed as bytes?? // FIXME TEMPORARILY LIMITED TO 3 bytes memory allParents = abi.encodePacked( _parents[0], _parents[1], _parents[2] ); /* Set value in Zer0net Db. */ _zer0netDb.setBytes(hash, allParents); /* Return success. */ return true; } /** * Set Token Provider */ function setTokenProvider( address _token, address _provider, bool _auth ) external onlyAuthBy0Admin returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _provider, '.has.auth.for.', _token )); /* Set value in Zer0net Db. */ _zer0netDb.setBool(hash, _auth); /* Return success. */ return true; } /** * Set Mining Target */ function _setMiningTarget( address _token, uint _target ) private returns (bool success) { /* Set hash. */ bytes32 hash = keccak256(abi.encodePacked( _namespace, '.', _token, '.target' )); /* Set value in Zer0net Db. */ _zer0netDb.setUint(hash, _target); /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initialize hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * InfinityPool Interface * * Retrieves the current InfinityPool interface, * using the aname record from Zer0netDb. */ function _infinityPool() private view returns ( InfinityPoolInterface infinityPool ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitypool'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityPool = InfinityPoolInterface(aname); } /** * InfinityWell Interface * * Retrieves the current InfinityWell interface, * using the aname record from Zer0netDb. */ function _infinityWell() private view returns ( InfinityWellInterface infinityWell ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.infinitywell'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ infinityWell = InfinityWellInterface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress(bytes _address) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Convert Bytes to Bytes32 */ function _bytesToBytes32( bytes _data ) private pure returns (bytes32 result) { /* Loop through each byte. */ for (uint i = 0; i < 32; i++) { /* Shift bytes onto result. */ result |= bytes32(_data[i] & 0xFF) >> (i * 8); } } /** * Convert Bytes32 to Bytes * * NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this, * which returns bytes. (https://ethereum.stackexchange.com/a/55963) */ function _bytes32ToBytes( bytes32 _data ) private pure returns (bytes result) { /* Pack the data. */ return abi.encodePacked(_data); } }
Mint/ Retrieve the current challenge. / Get mint digest. / The challenge digest must match the expected. / The digest must be smaller than the target. / Validate solution. / every so often, readjust difficulty. Dont readjust when deploying
function mint( address _token, bytes32 _digest, uint _nonce ) public returns (bool success) { uint challenge = getChallenge(_token); bytes32 digest = getMintDigest( challenge, msg.sender, _nonce ); if (digest != _digest) { revert('Oops! That solution is NOT valid.'); } if (uint(digest) > getTarget(_token)) { revert('Oops! That solution is NOT valid.'); } _namespace, '.', digest, '.solutions' )); if (solution != 0x0) { revert('Oops! That solution is a DUPLICATE.'); } _namespace, '.', _token, '.generation' )); _namespace, '.', _token, '.generations.per.adjustment' )); if (generation % genPerAdjustment == 0) { _reAdjustDifficulty(_token); } _namespace, '.', _token, '.challenge' )); hash, _bytes32ToBytes(blockhash(block.number - 1)) ); _token, msg.sender, rewardAmount ); msg.sender, rewardAmount, generation, ); }
902,590
// File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view 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/ownership/Ownable.sol pragma solidity ^0.5.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. * * 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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ 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/Address.sol pragma solidity ^0.5.5; /** * @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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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 ERC20;` 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)); } 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "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: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.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 {ERC20Mintable}. * * 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; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _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 { require(account != address(0), "ERC20: mint to the zero address"); _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 { require(account != address(0), "ERC20: burn from the zero address"); _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 is 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 { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * 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; } } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: @openzeppelin/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @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. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.0; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is ERC20, 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 increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: @openzeppelin/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.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). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } // File: contracts/NasiToken.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.14; contract NasiToken is Ownable, ERC20Detailed('NasiToken', 'NAS', 18), ERC20Pausable, ERC20Burnable, ERC20Mintable { function mint(address _to, uint256 _amount) public onlyMinter returns (bool) { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); return true; } mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "NASI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "NASI::delegateBySig: invalid nonce"); require(now <= expiry, "NASI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "NASI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying NASIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "NASI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/NasiLiquidityPoolFactory.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.14; interface IMigrator { /** * Perform LP token migration from legacy UniswapV2 to NasiSwap. * Take the current LP token address and return the new LP token address. * Migrator should have full access to the caller's LP token. * XXX Migrator must have allowance access to UniswapV2 LP tokens. * NasiSwap must mint EXACTLY the same amount of NasiSwap LP tokens or * else something bad will happen. Traditional UniswapV2 does not * do that so be careful! */ function migrate(address token) external returns (address); } contract NasiLiquidityPoolFactory is Ownable { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; /** * @param amountOfLpToken * @param rewardDebt */ struct UserInfo { uint256 amountOfLpToken; uint256 rewardDebt; } struct PoolInfo { address lpTokenAddress; uint256 allocationPoint; uint256 lastRewardBlock; uint256 accumulatedNasiPerShare; } NasiToken public nasiToken; uint256 public nasiPerBlock; uint256 public endBlock; uint256 public endBlockWeek1; uint256 public endBlockWeek2; uint256 public endBlockWeek3; uint256 public endBlockWeek4; uint256 public poolCounter; address public migrator; address public devaddr; mapping (uint256 => PoolInfo) public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocationPoint; uint256 public startBlock; 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( address _nasiAddress, address _devaddr, uint256 _nasiPerBlock, uint256 _startBlock ) public { nasiToken = NasiToken(_nasiAddress); devaddr = _devaddr; nasiPerBlock = _nasiPerBlock; startBlock = _startBlock; endBlockWeek1 = _startBlock.add(45500); endBlockWeek2 = endBlockWeek1.add(45500); endBlockWeek3 = endBlockWeek2.add(45500); endBlockWeek4 = endBlockWeek3.add(45500); endBlock = _startBlock.add(1137500); } /** * @notice Set the migrator contract. Can only be called by the owner. */ function setMigrator(address _migrator) public onlyOwner { require(_migrator != address(0), 'Migrator can not equal address0'); migrator = _migrator; } /** * @notice Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. */ function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = IERC20(pool.lpTokenAddress); uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); address newLpToken = IMigrator(migrator).migrate(pool.lpTokenAddress); require(bal == IERC20(newLpToken).balanceOf(address(this)), "migrate: bad"); pool.lpTokenAddress = newLpToken; } /** * @notice Deposit LP tokens to Factory for nasi allocation. */ function deposit(uint256 _pid, uint256 _amount) public { require(_pid <= poolCounter, 'Invalid pool id!'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amountOfLpToken > 0) { uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); if(pending > 0) { _safeNasiTransfer(msg.sender, pending); } } IERC20(pool.lpTokenAddress).safeTransferFrom(address(msg.sender), address(this), _amount); user.amountOfLpToken = user.amountOfLpToken.add(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); emit Deposit(msg.sender, _pid, _amount); } /** * @notice Add a new lp to the pool. Can only be called by the owner. */ function addLpToken(uint256 _allocationPoint, address _lpTokenAddress, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } poolCounter++; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocationPoint = totalAllocationPoint.add(_allocationPoint); poolInfo[poolCounter] = PoolInfo( _lpTokenAddress, _allocationPoint, lastRewardBlock, 0 ); } function massUpdatePools() public { for (uint256 _pid = 1; _pid <= poolCounter; _pid++) { updatePool(_pid); } } /** * @notice 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 = IERC20(pool.lpTokenAddress).balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getBonusMultiplier(pool.lastRewardBlock, block.number); uint256 nasiReward = multiplier.mul(nasiPerBlock).mul(pool.allocationPoint).div(totalAllocationPoint); nasiToken.mint(address(this), nasiReward); nasiToken.mint(devaddr, nasiReward.div(50)); pool.accumulatedNasiPerShare = pool.accumulatedNasiPerShare.add(nasiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } /** * @notice Get the bonus multiply ratio at the initial time. */ function getBonusMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 week1 = _from <= endBlockWeek1 && _to > startBlock ? (Math.min(_to, endBlockWeek1) - Math.max(_from, startBlock)).mul(16) : 0; uint256 week2 = _from <= endBlockWeek2 && _to > endBlockWeek1 ? (Math.min(_to, endBlockWeek2) - Math.max(_from, endBlockWeek1)).mul(8) : 0; uint256 week3 = _from <= endBlockWeek3 && _to > endBlockWeek2 ? (Math.min(_to, endBlockWeek3) - Math.max(_from, endBlockWeek2)).mul(4) : 0; uint256 week4 = _from <= endBlockWeek4 && _to > endBlockWeek3 ? (Math.min(_to, endBlockWeek4) - Math.max(_from, endBlockWeek3)).mul(2) : 0; uint256 end = _from <= endBlock && _to > endBlockWeek4 ? (Math.min(_to, endBlock) - Math.max(_from, endBlockWeek4)) : 0; return week1.add(week2).add(week3).add(week4).add(end); } function pendingNasi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accumulatedNasiPerShare = pool.accumulatedNasiPerShare; uint256 lpSupply = IERC20(pool.lpTokenAddress).balanceOf(address(this)); if (lpSupply == 0) { return 0; } if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplierBonus = getBonusMultiplier(pool.lastRewardBlock, block.number); uint256 nasiReward = multiplierBonus.mul(nasiPerBlock).mul(pool.allocationPoint).div(totalAllocationPoint); accumulatedNasiPerShare = accumulatedNasiPerShare.add(nasiReward.mul(1e12).div(lpSupply)); } return (user.amountOfLpToken.mul(accumulatedNasiPerShare).sub(user.rewardDebt).div(1e12)); } /** * @notice Withdraw LP tokens from Factory */ function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amountOfLpToken >= _amount, "Not enough funds!"); updatePool(_pid); uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); _safeNasiTransfer(msg.sender, pending); user.amountOfLpToken = user.amountOfLpToken.sub(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amountOfLpToken; user.amountOfLpToken = 0; user.rewardDebt = 0; IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Update the given pool's NASI allocation point. Can only be called by the owner. function setAllocationPoint(uint256 _pid, uint256 _allocationPoint, bool _withUpdate) public onlyOwner { require(_pid <= poolCounter, 'Invalid pool id!'); if (_withUpdate) { massUpdatePools(); } totalAllocationPoint = totalAllocationPoint.sub(poolInfo[_pid].allocationPoint).add(_allocationPoint); poolInfo[_pid].allocationPoint = _allocationPoint; } function _safeNasiTransfer(address _to, uint256 _amount) internal { uint256 nasiBalance = nasiToken.balanceOf(address(this)); if (_amount > nasiBalance) { nasiToken.transfer(_to, nasiBalance); } else { nasiToken.transfer(_to, _amount); } } function _safeNasiBurn(uint256 _amount) internal { uint256 nasiBalance = nasiToken.balanceOf(address(this)); if (_amount > nasiBalance) { nasiToken.burn(nasiBalance); } else { nasiToken.burn(_amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "NASI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
54,987
// 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/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 (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 pragma solidity 0.8.7; import "./BaseAccumulator.sol"; /// @title A contract that accumulates sanUSDC_EUR rewards and notifies them to the LGV4 /// @author StakeDAO contract AngleAccumulator is BaseAccumulator { /* ========== CONSTRUCTOR ========== */ constructor(address _tokenReward) BaseAccumulator(_tokenReward) {} /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Claims rewards from the locker and notify an amount to the LGV4 /// @param _amount amount to notify after the claim function claimAndNotify(uint256 _amount) external { require(locker != address(0), "locker not set"); ILocker(locker).claimRewards(tokenReward, address(this)); _notifyReward(tokenReward, _amount); } /// @notice Claims rewards from the locker and notify all to the LGV4 function claimAndNotifyAll() external { require(locker != address(0), "locker not set"); ILocker(locker).claimRewards(tokenReward, address(this)); uint256 amount = IERC20(tokenReward).balanceOf(address(this)); _notifyReward(tokenReward, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/ILiquidityGauge.sol"; import "../interfaces/ILocker.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title A contract that defines the functions shared by all accumulators /// @author StakeDAO contract BaseAccumulator { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address public governance; address public locker; address public tokenReward; address public gauge; /* ========== EVENTS ========== */ event GaugeSet(address oldGauge, address newGauge); event RewardNotified(address gauge, address tokenReward, uint256 amount); event LockerSet(address oldLocker, address newLocker); event GovernanceSet(address oldGov, address newGov); event TokenRewardSet(address oldTr, address newTr); event TokenDeposited(address token, uint256 amount); event ERC20Rescued(address token, uint256 amount); /* ========== CONSTRUCTOR ========== */ constructor(address _tokenReward) { tokenReward = _tokenReward; governance = msg.sender; } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Notify the reward using an extra token /// @param _tokenReward token address to notify /// @param _amount amount to notify function notifyExtraReward(address _tokenReward, uint256 _amount) external { require(msg.sender == governance, "!gov"); _notifyReward(_tokenReward, _amount); } /// @notice Notify the reward using all balance of extra token /// @param _tokenReward token address to notify function notifyAllExtraReward(address _tokenReward) external { require(msg.sender == governance, "!gov"); uint256 amount = IERC20(_tokenReward).balanceOf(address(this)); _notifyReward(_tokenReward, amount); } /// @notice Notify the new reward to the LGV4 /// @param _tokenReward token to notify /// @param _amount amount to notify function _notifyReward(address _tokenReward, uint256 _amount) internal { require(gauge != address(0), "gauge not set"); require(_amount > 0, "set an amount > 0"); uint256 balanceBefore = IERC20(_tokenReward).balanceOf(address(this)); require(balanceBefore >= _amount, "amount not enough"); if (ILiquidityGauge(gauge).reward_data(_tokenReward).distributor != address(0)) { IERC20(_tokenReward).approve(gauge, _amount); ILiquidityGauge(gauge).deposit_reward_token(_tokenReward, _amount); uint256 balanceAfter = IERC20(_tokenReward).balanceOf(address(this)); require(balanceBefore - balanceAfter == _amount, "wrong amount notified"); emit RewardNotified(gauge, _tokenReward, _amount); } } /// @notice Deposit token into the accumulator /// @param _token token to deposit /// @param _amount amount to deposit function depositToken(address _token, uint256 _amount) external { require(_amount > 0, "set an amount > 0"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); emit TokenDeposited(_token, _amount); } /// @notice Sets gauge for the accumulator which will receive and distribute the rewards /// @dev Can be called only by the governance /// @param _gauge gauge address function setGauge(address _gauge) external { require(msg.sender == governance, "!gov"); require(_gauge != address(0), "can't be zero address"); emit GaugeSet(gauge, _gauge); gauge = _gauge; } /// @notice Allows the governance to set the new governance /// @dev Can be called only by the governance /// @param _governance governance address function setGovernance(address _governance) external { require(msg.sender == governance, "!gov"); require(_governance != address(0), "can't be zero address"); emit GovernanceSet(governance, _governance); governance = _governance; } /// @notice Allows the governance to set the locker /// @dev Can be called only by the governance /// @param _locker locker address function setLocker(address _locker) external { require(msg.sender == governance, "!gov"); require(_locker != address(0), "can't be zero address"); emit LockerSet(locker, _locker); locker = _locker; } /// @notice Allows the governance to set the token reward /// @dev Can be called only by the governance /// @param _tokenReward token reward address function setTokenReward(address _tokenReward) external { require(msg.sender == governance, "!gov"); require(_tokenReward != address(0), "can't be zero address"); emit TokenRewardSet(tokenReward, _tokenReward); tokenReward = _tokenReward; } /// @notice A function that rescue any ERC20 token /// @param _token token address /// @param _amount amount to rescue /// @param _recipient address to send token rescued function rescueERC20( address _token, uint256 _amount, address _recipient ) external { require(msg.sender == governance, "!gov"); require(_amount > 0, "set an amount > 0"); require(_recipient != address(0), "can't be zero address"); IERC20(_token).safeTransfer(_recipient, _amount); emit ERC20Rescued(_token, _amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface ILiquidityGauge { struct Reward { address token; address distributor; uint256 period_finish; uint256 rate; uint256 last_update; uint256 integral; } // solhint-disable-next-line function deposit_reward_token(address _rewardToken, uint256 _amount) external; // solhint-disable-next-line function claim_rewards_for(address _user, address _recipient) external; // // solhint-disable-next-line // function claim_rewards_for(address _user) external; // solhint-disable-next-line function deposit(uint256 _value, address _addr) external; // solhint-disable-next-line function reward_tokens(uint256 _i) external view returns(address); // solhint-disable-next-line function reward_data(address _tokenReward) external view returns(Reward memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ILocker { function createLock(uint256, uint256) external; function increaseAmount(uint256) external; function increaseUnlockTime(uint256) external; function release() external; function claimRewards(address,address) external; function claimFXSRewards(address) external; function execute( address, uint256, bytes calldata ) external returns (bool, bytes memory); function setGovernance(address) external; function voteGaugeWeight(address, uint256) external; function setAngleDepositor(address) external; function setFxsDepositor(address) external; }
Notify the reward using all balance of extra token _tokenReward token address to notify
function notifyAllExtraReward(address _tokenReward) external { require(msg.sender == governance, "!gov"); uint256 amount = IERC20(_tokenReward).balanceOf(address(this)); _notifyReward(_tokenReward, amount); }
11,859,217
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: contracts/tokenIssueContract.sol // Written by Metabridge - https://www.metabridgeagency.com // We are a community of passionate <humans /> building a distributed world pragma solidity ^0.8.0; /// @author MetaBridge Agency LLC /// @title The bank for the Sheeba play to earn rewards. contract SheebaGameTokenBank { IERC20 public erc20Token; address public owner; string public name = "Sheeba Game Token Bank"; mapping(address => bool) public admins; mapping(address => uint256) public earners; mapping(address => bool) public blockedAddresses; constructor(address _erc20Token) { erc20Token = IERC20(_erc20Token); owner = msg.sender; // Set the owner as a dev admins[msg.sender] = true; } /// Return the users token balance. /// @param userAddress the address to check. /// @return the users token balance. function getTokenBalance(address userAddress) public view returns(uint256) { return erc20Token.balanceOf(userAddress); } /// Return the contracts balance of tokens. /// @return the contracts balance of tokens. function getContractBalance() public view returns(uint256) { return getTokenBalance(address(this)); } /// Return the users reward balance. /// @param userAddress the address to check. /// @return the users reward balance. function getRewardsBalance(address userAddress) public view returns(uint256) { return earners[userAddress]; } /// Store 'totalSheeb'. /// @param userAddressToAdd the address to add. /// @param totalSheeb the amount of sheeb to add to the user. Not in full form decimal ex. 10 Tokens = 10 function addTokens(address userAddressToAdd, uint256 totalSheeb) public { // Check if admin require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN"); // Start earners[userAddressToAdd] = earners[userAddressToAdd] += totalSheeb * 10 ** 18; } /// Store 'totalSheeb' per user. /// @param userAddresses the addresses to add. /// @param points the points to add. Not in full form decimal ex. 10 Tokens = 10 function addTokensMultiple(address[] memory userAddresses, uint256[] memory points) public { // Check if admin require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN"); require(userAddresses.length == points.length, "Unequal arrays"); // Start for (uint i=0; i<userAddresses.length; i++) { earners[userAddresses[i]] = earners[userAddresses[i]] += points[i] * 10 ** 18; } } /// Store 'userAddressToAdd' as either bot or not. /// @param userAddressToAdd the address to add or remove. /// @param isBot the indication of whether or not this address is a bot. function userIsBot(address userAddressToAdd, bool isBot) public { // Check if admin require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN"); // Start blockedAddresses[userAddressToAdd] = isBot; } /// Store 'newAdmin' as admin. /// @param newAdmin the address to add. function addAdmin(address newAdmin) public { require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN"); // Any admin can remove the another require(newAdmin != msg.sender, "Cannot add yourself as admin."); admins[newAdmin] = true; } /// Store 'adminToRemove' as admin. /// @param adminToRemove the address to remove. function removeAdmin(address adminToRemove) public { require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN"); // Any admin can remove the another require(adminToRemove != msg.sender, "Cannot remove yourself as admin."); admins[adminToRemove] = false; } /// Remove the tokens from the contract in case of upgrade or contract issue. function retrieveRewardTokens() public { require(admins[msg.sender] == true, "YOU ARE NOT AN ADMIN"); uint256 contractBalance = getTokenBalance(address(this)); erc20Token.transfer(msg.sender, contractBalance); } /// Send the tokens to the users wallet. function recieveReward() public { uint256 amountToSend = earners[msg.sender]; // Get balance of contract uint256 contractBalance = getTokenBalance(address(this)); require(amountToSend > 0, "You have not earned any tokens."); require(contractBalance >= amountToSend, "Not enough tokens in the contract. Please contact the DEV team."); earners[msg.sender] = 0; erc20Token.transfer(msg.sender, amountToSend); } }
Return the contracts balance of tokens. return the contracts balance of tokens.
function getContractBalance() public view returns(uint256) { return getTokenBalance(address(this)); }
122,632
// Squishiverse by FourLeafClover (www.squishiverse.com) - Bridge Squishiverse Item // MMMMMW0dxxxdkXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMM0cdKNNKloXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMKolk00kloXMWNK0KKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMXkxxddkXWKdoddxxxxkOKXXXNNWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMWWMMMXllO000KKKOkxxxxkkkkkkkkkO0KNWMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMKccO000000KKXNNNNNNNXXXK0OkkkkkkOKNMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMN0xocck0000000000KKKKXXXNNNNWWWWNX0kkkkOKWMMMMMMMMMMMMMMMMM // MMMMMMMMWXkoodkOOO00000000000000000000KKXXNNWWWMWXOxxk0NMMMMMMMMMMMMMM // MMMMMMWKxlokO000000000000000000000000000000KXWMMMMMMN0kxkKWMMMMMMMMMMM // MMMMMXxlok0000000000000000000000000000000000KNMMMMMMMMMN0xxONMMMMMMMMM // MMMW0ook0000000000000000000000000000000000000XWMMMMMMMMMMWKxdONMMMMMMM // MMWkldO000000000000000000000000000000000000000KXNWMMWNNWMMMWKxd0WMMMMM // MNxcx00000000000000000000000000000000000000000000KXOc,':ONWWMW0dkNMMMM // Wkcd0000000000000000Oo;,:dO00000000000000000000000d. .oXWWMMXxdKMMM // KloO000000000000000k; .:k000000000000000000000O: ;'.dNNWWMNxoKMM // dck000000000000000Oc '..lO00000000000000000000O: ;KNNWWMNxoXM // lo0000000000000000x' .:;.;k00000000000000000000Ol. 'ONNNWWMXdxN // cd0000000000000000x' ,k000000000000000000000x' .xNNNNWWM0o0 // cd0000000000000000x' ;O000000000000000000000Oo. ;kXNNNNWMNdd // cd0000000000000000k; .lO0000000000000000000000Od:'.,ck0KXNNNWWWko // olO0000000000000000d' 'x000000000000000O0000000000Okxk000XNNNNWMOl // kcx00000000000000000x:...;xOOxkO00000OOxolc::cclooodolccok000KNNNNWMOl // XolO00000000000000000OkkkO00kollccclcc:;,,;;;;,,,,,'.,lk00000KNNNNWMko // M0loO0000000000000000000000000Oko:,''',,,,,,,,,,,;;:okO000000KNNNNWWxd // MWOloO000000000000000000000000000OkkxdddddddoodddxkO000000000XNNNWMKoO // MMW0lok00000000000000000000000000000000000000000000000000000KXNNWWNddN // MMMMXdlxO000000000000000000000000000000000000000000000000000XNNNWNxdXM // MMMMMWOolxO000000000000000000000000000000000000000000000000KNNNWKxdKMM // MMMMMMMNOoldO000000000000000000000000000000000000000000000KNNNXkdkNMMM // MMMMMMMMMN0dooxO00000000000000000000000000000000000000000KXKkxdkXWMMMM // MMMMMMMMMMMWXOxdooxkO0000000000000000000000000000000Okxxdxxxk0NMMMMMMM // MMMMMMMMMMMMMMMNKOxdddoooddxxxxkkkkkkkxxxxxddddoooodddxkOKNWMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMWNKOxdollccccccccccccccccllodxk0KNWMMMMMMMMMMMMMMMM // Development help from @lozzereth (www.allthingsweb3.com) // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import {IBridgeSquishiverseItem} from "./interfaces/IBridgeSquishiverseItem.sol"; import {ISquishiverseItem} from "./interfaces/ISquishiverseItem.sol"; /// @dev The bridge is paused error BridgeSquishiverseItem__BridgePaused(); /// @dev Signature claim is invalid error BridgeSquishiverseItem__InvalidClaimSignature(); /// @dev The nonce specified is invalid error BridgeSquishiverseItem__InvalidClaimNonce(); /// @dev Cancel functionality is disabled error BridgeSquishiverseItem__CancellingDisabled(); /// @dev The id and qty do not match items error BridgeSquishiverseItem__IdAndQtyMismatch(); contract BridgeSquishiverseItem is IBridgeSquishiverseItem, Ownable { using ECDSA for bytes32; /// @dev Oracle to sign the addresses address public oracleAddress; /// @dev 1155 Token we are bridging ISquishiverseItem public immutable erc1155Address; /// @dev Bridge pausibility bool public paused; /// @dev Claims nonces stored against addresses mapping(address => uint256) public claimNonce; /// @dev Cancellable bool public cancellable; constructor(ISquishiverseItem _erc1155Address, address _oracleAddress) { erc1155Address = _erc1155Address; oracleAddress = _oracleAddress; } modifier idAndAmountsMatch( uint256[] memory _ids, uint256[] memory _amounts ) { if (_ids.length != _amounts.length) { revert BridgeSquishiverseItem__IdAndQtyMismatch(); } _; } /** * @dev Swap a token into the the bridge */ function swap( uint256[] memory ids, uint256[] memory amounts, uint256 nonce ) external notPaused idAndAmountsMatch(ids, amounts) { for (uint256 id; id < ids.length; id++) { ISquishiverseItem(erc1155Address).burn( msg.sender, ids[id], amounts[id] ); } emit BridgedTokens(msg.sender, ids, amounts, nonce); } /** * @dev Claim an amount from the bridge */ function claim( address recipient, uint256[] memory ids, uint256[] memory amounts, uint256 oldBlock, uint256 newBlock, bytes calldata signature ) external notPaused hasValidNonce(recipient, oldBlock, newBlock) idAndAmountsMatch(ids, amounts) { bytes32 data = keccak256( abi.encodePacked(recipient, ids, amounts, oldBlock, newBlock) ); if (data.toEthSignedMessageHash().recover(signature) != oracleAddress) { revert BridgeSquishiverseItem__InvalidClaimSignature(); } claimNonce[recipient] = newBlock; for (uint256 id; id < ids.length; id++) { ISquishiverseItem(erc1155Address).mint( recipient, ids[id], amounts[id] ); } } modifier hasValidNonce( address _recipient, uint256 _oldBlock, uint256 _newBlock ) { if ( _oldBlock != claimNonce[_recipient] || _oldBlock >= block.number || _newBlock <= _oldBlock ) { revert BridgeSquishiverseItem__InvalidClaimNonce(); } _; } /** * @dev Cancels a claim for an address */ function cancelClaimAdmin( address _address, uint256 oldBlock, uint256 newBlock ) external onlyOwner hasValidNonce(_address, oldBlock, newBlock) { claimNonce[_address] = newBlock; emit CancelClaim(_address, oldBlock, newBlock); } /** * @dev Cancel claim as a user */ function cancelClaim(uint256 oldBlock, uint256 newBlock) external cancelEnabled hasValidNonce(msg.sender, oldBlock, newBlock) { claimNonce[msg.sender] = newBlock; emit CancelClaim(msg.sender, oldBlock, newBlock); } modifier cancelEnabled() { if (!cancellable) { revert BridgeSquishiverseItem__CancellingDisabled(); } _; } /** * @dev Toggles the cancellable state */ function toggleCancellable() external onlyOwner { cancellable = !cancellable; } /** * @dev Set the oracle address to verify the data */ function setOracleAddress(address _oracleAddress) external onlyOwner { oracleAddress = _oracleAddress; } /** * @dev Set pause state of the bridge */ function togglePaused() external onlyOwner { paused = !paused; } modifier notPaused() { if (paused) revert BridgeSquishiverseItem__BridgePaused(); _; } /** * @dev Destroy the smart contract */ function destroySmartContract(address payable _to) external onlyOwner { selfdestruct(_to); } } // 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 (last updated v4.5.0) (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 = 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)); } } // Squishiverse by FourLeafClover (www.squishiverse.com) - Bridge Squishiverse Item Interface // MMMMMW0dxxxdkXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMM0cdKNNKloXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMKolk00kloXMWNK0KKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMXkxxddkXWKdoddxxxxkOKXXXNNWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMWWMMMXllO000KKKOkxxxxkkkkkkkkkO0KNWMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMKccO000000KKXNNNNNNNXXXK0OkkkkkkOKNMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMN0xocck0000000000KKKKXXXNNNNWWWWNX0kkkkOKWMMMMMMMMMMMMMMMMM // MMMMMMMMWXkoodkOOO00000000000000000000KKXXNNWWWMWXOxxk0NMMMMMMMMMMMMMM // MMMMMMWKxlokO000000000000000000000000000000KXWMMMMMMN0kxkKWMMMMMMMMMMM // MMMMMXxlok0000000000000000000000000000000000KNMMMMMMMMMN0xxONMMMMMMMMM // MMMW0ook0000000000000000000000000000000000000XWMMMMMMMMMMWKxdONMMMMMMM // MMWkldO000000000000000000000000000000000000000KXNWMMWNNWMMMWKxd0WMMMMM // MNxcx00000000000000000000000000000000000000000000KXOc,':ONWWMW0dkNMMMM // Wkcd0000000000000000Oo;,:dO00000000000000000000000d. .oXWWMMXxdKMMM // KloO000000000000000k; .:k000000000000000000000O: ;'.dNNWWMNxoKMM // dck000000000000000Oc '..lO00000000000000000000O: ;KNNWWMNxoXM // lo0000000000000000x' .:;.;k00000000000000000000Ol. 'ONNNWWMXdxN // cd0000000000000000x' ,k000000000000000000000x' .xNNNNWWM0o0 // cd0000000000000000x' ;O000000000000000000000Oo. ;kXNNNNWMNdd // cd0000000000000000k; .lO0000000000000000000000Od:'.,ck0KXNNNWWWko // olO0000000000000000d' 'x000000000000000O0000000000Okxk000XNNNNWMOl // kcx00000000000000000x:...;xOOxkO00000OOxolc::cclooodolccok000KNNNNWMOl // XolO00000000000000000OkkkO00kollccclcc:;,,;;;;,,,,,'.,lk00000KNNNNWMko // M0loO0000000000000000000000000Oko:,''',,,,,,,,,,,;;:okO000000KNNNNWWxd // MWOloO000000000000000000000000000OkkxdddddddoodddxkO000000000XNNNWMKoO // MMW0lok00000000000000000000000000000000000000000000000000000KXNNWWNddN // MMMMXdlxO000000000000000000000000000000000000000000000000000XNNNWNxdXM // MMMMMWOolxO000000000000000000000000000000000000000000000000KNNNWKxdKMM // MMMMMMMNOoldO000000000000000000000000000000000000000000000KNNNXkdkNMMM // MMMMMMMMMN0dooxO00000000000000000000000000000000000000000KXKkxdkXWMMMM // MMMMMMMMMMMWXOxdooxkO0000000000000000000000000000000Okxxdxxxk0NMMMMMMM // MMMMMMMMMMMMMMMNKOxdddoooddxxxxkkkkkkkxxxxxddddoooodddxkOKNWMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMWNKOxdollccccccccccccccccllodxk0KNWMMMMMMMMMMMMMMMM // Development help from @lozzereth (www.allthingsweb3.com) // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; error BridgePaused(); error InvalidClaimSignature(); error InvalidClaimNonce(); error CancellingDisabled(); interface IBridgeSquishiverseItem { // Events event BridgedTokens( address from, uint256[] ids, uint256[] amounts, uint256 nonce ); event CancelClaim(address from, uint256 oldBlock, uint256 newBlock); /** * @dev Swap tokens into the bridge */ function swap( uint256[] memory ids, uint256[] memory amounts, uint256 nonce ) external; /** * @dev Claim items from the bridge */ function claim( address recipient, uint256[] memory ids, uint256[] memory amounts, uint256 oldBlock, uint256 newBlock, bytes calldata signature ) external; /** * @dev Cancels a claim for an address */ function cancelClaimAdmin( address _address, uint256 oldBlock, uint256 newBlock ) external; /** * @dev Cancel claim as a user */ function cancelClaim(uint256 oldBlock, uint256 newBlock) external; /** * @dev Toggles the cancellable state */ function toggleCancellable() external; /** * @dev Set the oracle address to verify the data */ function setOracleAddress(address _oracleAddress) external; /** * @dev Set pause state of the bridge */ function togglePaused() external; } // Squishiverse by FourLeafClover (www.squishiverse.com) - Squishiverse Item Interface // MMMMMW0dxxxdkXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMM0cdKNNKloXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMKolk00kloXMWNK0KKNWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMXkxxddkXWKdoddxxxxkOKXXXNNWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMWWMMMXllO000KKKOkxxxxkkkkkkkkkO0KNWMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMKccO000000KKXNNNNNNNXXXK0OkkkkkkOKNMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMN0xocck0000000000KKKKXXXNNNNWWWWNX0kkkkOKWMMMMMMMMMMMMMMMMM // MMMMMMMMWXkoodkOOO00000000000000000000KKXXNNWWWMWXOxxk0NMMMMMMMMMMMMMM // MMMMMMWKxlokO000000000000000000000000000000KXWMMMMMMN0kxkKWMMMMMMMMMMM // MMMMMXxlok0000000000000000000000000000000000KNMMMMMMMMMN0xxONMMMMMMMMM // MMMW0ook0000000000000000000000000000000000000XWMMMMMMMMMMWKxdONMMMMMMM // MMWkldO000000000000000000000000000000000000000KXNWMMWNNWMMMWKxd0WMMMMM // MNxcx00000000000000000000000000000000000000000000KXOc,':ONWWMW0dkNMMMM // Wkcd0000000000000000Oo;,:dO00000000000000000000000d. .oXWWMMXxdKMMM // KloO000000000000000k; .:k000000000000000000000O: ;'.dNNWWMNxoKMM // dck000000000000000Oc '..lO00000000000000000000O: ;KNNWWMNxoXM // lo0000000000000000x' .:;.;k00000000000000000000Ol. 'ONNNWWMXdxN // cd0000000000000000x' ,k000000000000000000000x' .xNNNNWWM0o0 // cd0000000000000000x' ;O000000000000000000000Oo. ;kXNNNNWMNdd // cd0000000000000000k; .lO0000000000000000000000Od:'.,ck0KXNNNWWWko // olO0000000000000000d' 'x000000000000000O0000000000Okxk000XNNNNWMOl // kcx00000000000000000x:...;xOOxkO00000OOxolc::cclooodolccok000KNNNNWMOl // XolO00000000000000000OkkkO00kollccclcc:;,,;;;;,,,,,'.,lk00000KNNNNWMko // M0loO0000000000000000000000000Oko:,''',,,,,,,,,,,;;:okO000000KNNNNWWxd // MWOloO000000000000000000000000000OkkxdddddddoodddxkO000000000XNNNWMKoO // MMW0lok00000000000000000000000000000000000000000000000000000KXNNWWNddN // MMMMXdlxO000000000000000000000000000000000000000000000000000XNNNWNxdXM // MMMMMWOolxO000000000000000000000000000000000000000000000000KNNNWKxdKMM // MMMMMMMNOoldO000000000000000000000000000000000000000000000KNNNXkdkNMMM // MMMMMMMMMN0dooxO00000000000000000000000000000000000000000KXKkxdkXWMMMM // MMMMMMMMMMMWXOxdooxkO0000000000000000000000000000000Okxxdxxxk0NMMMMMMM // MMMMMMMMMMMMMMMNKOxdddoooddxxxxkkkkkkkxxxxxddddoooodddxkOKNWMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMWNKOxdollccccccccccccccccllodxk0KNWMMMMMMMMMMMMMMMM // Development help from @lozzereth (www.allthingsweb3.com) // SPDX-License-Identifier: MIT pragma solidity ^0.8; interface ISquishiverseItem { /** * @dev Mint as bridge/owner */ function mint( address account, uint256 id, uint256 value ) external; /** * @dev Burn as an authorised operator */ function burn( address account, uint256 id, uint256 value ) external; } // 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/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: 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); }
Destroy the smart contract/
function destroySmartContract(address payable _to) external onlyOwner { selfdestruct(_to); }
1,203,327
./partial_match/1/0x4FE12B27Af2D19516d670473310093900dd71A71/sources/GFYToken.sol
Only the contract owner can enable trading
function enableTrading() external onlyOwner { tradingEnabled = true; }
16,037,222
./full_match/1/0xcE9b49b0d4FE456aD6E4a1b7e4bBdD0699400Ef9/sources/src/vaults/borrowing/BorrowingVaultUpgradeable.sol
@inheritdoc IVaultUpgradeable
function debtDecimals() public view override returns (uint8) { return _debtDecimals; }
2,939,904
./full_match/1/0x479bb758024d768e4153031AC3F8Cd1e458Bd6c2/sources/contracts/OracleAggregator.sol
modify nrOfDecimlas and amount to follow stableCoin's nrOfDecimals
function _matchStableCoinDecimal( address stableCoinAddress, uint256 amount, uint256 nrOfDecimals, uint256 padding, uint256 returnRateA, uint256 returnRateB ) private view returns (uint256 returnAmount) { uint256 div = _nrOfDecimalsUSD[stableCoinAddress] > nrOfDecimals ? 10**(_nrOfDecimalsUSD[stableCoinAddress].sub(nrOfDecimals)) : 10**(nrOfDecimals.sub(_nrOfDecimalsUSD[stableCoinAddress])); returnAmount = _nrOfDecimalsUSD[stableCoinAddress] > nrOfDecimals ? amount.mul(returnRateA.mul(10**padding)).div(returnRateB).mul(div) : amount.mul(returnRateA.mul(10**padding)).div(returnRateB).div(div); }
8,436,455
./full_match/80001/0xf6D2a1306F24799f5BB24cB755E7c8F3471C05Ce/sources/EdFiContract.sol
generate the uniswap pair path of token -> wBNB
function _distributeForBNB(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapRouter.WETH(); _approve(address(this), address(uniswapRouter), tokenAmount); (bool success, ) = payable(address(uniswapRouter)).call( abi.encodeWithSignature( "swapExactTokensForETHSupportingFeeOnTransferTokens(uint256,uint256,address[],address,uint256)", tokenAmount, path, block.timestamp ) ); if (success) { emit SwapTokensForBNB(tokenAmount, path); } }
5,579,119
./full_match/1/0xe3aF60f1F08e489503d9827210c73E468400c7ec/sources/browser/Untitled.sol
withdrawer This function allows users to withdraw ETH tokenIds - the tokenIds from which to withdraw ether
function withdrawETH(uint256[] calldata tokenIds) external { uint i; for (i = 0;i < tokenIds.length;i++){ require(msg.sender == ownerOf(tokenIds[i])); uint amt = balanceOfETH[tokenIds[i]]; balanceOfETH[tokenIds[i]] = 0; require(success, "Transfer failed."); } }
9,724,338
pragma solidity ^0.4.2; contract ProofOfExistence { mapping (bytes32 => bool) private proofs; // store a proof of existence in the contract state function storeProof(bytes32 proof) { proofs[proof] = true; } // calculate and store the proof for a document function notarize(string document) constant returns (bool) { var proof = calculateProof(document); storeProof(proof); return } // helper function to get a document's sha256 function calculateProof(string document) constant returns (bytes32) { return sha256(document); } // check if a document has been notarized function checkDocument(string document) constant returns (bool) { var proof = calculateProof(document); return hasProof(proof); } // returns true if proof is stored function hasProof(bytes32 proof) constant returns(bool) { return proofs[proof]; } }
returns true if proof is stored
function hasProof(bytes32 proof) constant returns(bool) { return proofs[proof]; }
7,305,081
./full_match/137/0x8Ef559Eb7233BeAE8078Df40490D4CFF4AB5718F/sources/ArkenDexV1.sol
ETH => TOKEN TOKEN => ETH
function _tradeIDfyn( IERC20 _src, IERC20 _dest, uint256 inputAmount, uint256 minOutputAmount, address[] memory paths, address to, address dexAddr ) private returns (uint256[] memory amounts) { IUniswapV2Router02 uniRouter = IUniswapV2Router02(dexAddr); if (_ETH_ == address(_src)) { if (paths[0] == address(_ETH_)) { paths[0] = address(_WETH_DFYN_); } minOutputAmount, paths, to, _DEADLINE_ ); if (paths[paths.length - 1] == address(_ETH_)) { paths[paths.length - 1] = address(_WETH_DFYN_); } _src.safeApprove(dexAddr, inputAmount); amounts = uniRouter.swapExactTokensForETH( inputAmount, minOutputAmount, paths, to, _DEADLINE_ ); amounts = uniRouter.swapExactTokensForTokens( inputAmount, minOutputAmount, paths, to, _DEADLINE_ ); } }
3,736,418
./full_match/1/0x9f60a931c50596632E220384Ad7e90D2e9Eb7031/sources/Dorkland.sol
See {IERC20-allowance}./
function allowance( address owner, address spender ) public view virtual returns (uint256) { return _allowances[owner][spender]; }
2,940,524
./partial_match/8453/0x697813e9eFdF48E9c299ec635F86f98665252eBa/sources/BaseswapRouter.sol
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, "BaseswapLibrary: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "BaseswapLibrary: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; }
16,802,537
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import {ExecutionManager} from "../ExecutionManager.sol"; /** * @title SimpleCall * @notice A simple contract testing the execution manager's CALL. */ contract SimpleCall { address executionManagerAddress; /** * Constructor currently accepts an execution manager & stores that in storage. * Note this should be the only storage that this contract ever uses & it should be replaced * by a hardcoded value once we have the transpiler. */ constructor(address _executionManagerAddress) public { executionManagerAddress = _executionManagerAddress; } // expects _targetContract (address as bytes32), _calldata (variable-length bytes). // returns variable-length bytes result. function makeCall() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 methodId = keccak256("ovmCALL()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) // replace the first 4 bytes with the right methodID mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) // overwrite call params let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } } // expects _targetContract (address as bytes32), _calldata (variable-length bytes). // returns variable-length bytes result. function makeStaticCall() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 methodId = keccak256("ovmSTATICCALL()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) // replace the first 4 bytes with the right methodID mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) // overwrite call params let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } } // expects _targetContract (address as bytes32), _calldata (variable-length bytes). // returns variable-length bytes result. function makeDelegateCall() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 methodId = keccak256("ovmDELEGATECALL()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) // replace the first 4 bytes with the right methodID mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) // overwrite call params let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } } // Does a call to ovmSSTORE, assuming a 32-byte key and a 32-byte value are passed in function notStaticFriendlySSTORE() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 methodId = keccak256("ovmSSTORE()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) // replace the first 4 bytes with the right methodID mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) // overwrite call params let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } } // Does a call to ovmCREATE with provided contract initcode function notStaticFriendlyCREATE() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 methodId = keccak256("ovmCREATE()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) // replace the first 4 bytes with the right methodID mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) // overwrite call params let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } } // Does a call to ovmCREATE2 with provided contract salt and initcode function notStaticFriendlyCREATE2() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 methodId = keccak256("ovmCREATE2()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) // replace the first 4 bytes with the right methodID mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) // overwrite call params let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } } // Does a call to ovmSLOAD assuming a 32-byte KEY is passed in function staticFriendlySLOAD() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 methodId = keccak256("ovmSLOAD()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) // replace the first 4 bytes with the right methodID mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) // overwrite call params let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } } // expects 32-byte left-padded value for this contract's OVM address // does not return data function makeStaticCallThenCall() public { // bitwise right shift 28 * 8 bits so the 4 method ID bytes are in the right-most bytes bytes32 staticCallMethodId = keccak256("ovmSTATICCALL()") >> 224; bytes32 callMethodId = keccak256("ovmCALL()") >> 224; bytes32 sloadMethodId = keccak256("staticFriendlySLOAD()") >> 224; bytes32 sstoreMethodId = keccak256("notStaticFriendlySSTORE()") >> 224; address emAddr = executionManagerAddress; uint key = 1; uint value = 2; assembly { let myAddress := calldataload(4) function $writeMethodId(methodHash, writeToThis) { // replace the first 4 bytes with the right methodID mstore8(writeToThis, shr(24, methodHash)) mstore8(add(writeToThis, 1), shr(16, methodHash)) mstore8(add(writeToThis, 2), shr(8, methodHash)) mstore8(add(writeToThis, 3), methodHash) } let callBytes := mload(0x40) $writeMethodId(staticCallMethodId, callBytes) mstore(add(callBytes, 4), myAddress) $writeMethodId(sloadMethodId, add(callBytes, 0x24)) mstore(add(callBytes, 0x28), key) // overwrite call params let result := mload(0x40) let success := call(gas, emAddr, 0, callBytes, 0x48, result, 500000) if eq(success, 0) { revert(0,0) } // overwrite result to make next call callBytes := mload(0x40) //$writeMethodId(staticContextMethodId, callBytes) $writeMethodId(callMethodId, callBytes) mstore(add(callBytes, 4), myAddress) $writeMethodId(sstoreMethodId, add(callBytes, 0x24)) mstore(add(callBytes, 0x28), key) mstore(add(callBytes, 0x48), value) // overwrite call params result := mload(0x40) success := call(gas, emAddr, 0, callBytes, 0x68, result, 500000) if eq(success, 0) { revert(0,0) } } } }
expects _targetContract (address as bytes32), _calldata (variable-length bytes). returns variable-length bytes result. bitwise right shift 28 8 bits so the 4 method ID bytes are in the right-most bytes replace the first 4 bytes with the right methodID overwrite call params
function makeDelegateCall() public { bytes32 methodId = keccak256("ovmDELEGATECALL()") >> 224; address addr = executionManagerAddress; assembly { let callBytes := mload(0x40) calldatacopy(callBytes, 0, calldatasize) mstore8(callBytes, shr(24, methodId)) mstore8(add(callBytes, 1), shr(16, methodId)) mstore8(add(callBytes, 2), shr(8, methodId)) mstore8(add(callBytes, 3), methodId) let result := mload(0x40) let success := call(gas, addr, 0, callBytes, calldatasize, result, 500000) if eq(success, 0) { revert(0, 0) } return(result, returndatasize) } }
5,394,823
pragma solidity ^0.4.24; /** * This utility library was forked from https://github.com/o0ragman0o/LibCLL */ library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList { mapping (uint256 => mapping (bool => uint256)) list; uint256 length; uint256 index; } /** * @dev returns true if the list exists * @param self stored linked list from contract */ function listExists(LinkedList storage self) internal view returns (bool) { return self.length > 0; } /** * @dev returns true if the node exists * @param self stored linked list from contract * @param _node a node to search for */ function nodeExists(LinkedList storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract */ function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) { return self.length; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get */ function getNode(LinkedList storage self, uint256 _node) public view returns (bool, uint256, uint256) { if (!nodeExists(self,_node)) { return (false, 0, 0); } else { return (true, self.list[_node][PREV], self.list[_node][NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in */ function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool, uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } /** * @dev Can be used before `insert` to build an ordered list * @param self stored linked list from contract * @param _node an existing node to search from, e.g. HEAD. * @param _value value to seek * @param _direction direction to seek in * @return next first node beyond &#39;_node&#39; in direction `_direction` */ function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node first node for linking * @param _link node to link to in the _direction */ function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in */ function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); self.length++; return true; } else { return false; } } /** * @dev removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list */ function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; self.length--; return _node; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _index The node Id * @param _direction push to the head (NEXT) or tail (PREV) */ function add(LinkedList storage self, uint256 _index, bool _direction) internal returns (uint256) { insert(self, HEAD, _index, _direction); return self.index; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _direction push to the head (NEXT) or tail (PREV) */ function push(LinkedList storage self, bool _direction) internal returns (uint256) { self.index++; insert(self, HEAD, self.index, _direction); return self.index; } /** * @dev pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (NEXT) or the tail (PREV) */ function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } /** * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed from, address indexed to); /** * Constructor */ constructor() public { owner = msg.sender; } /** * @dev Only the owner of contract */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev transfer the ownership to other * - Only the owner can operate */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev Accept the ownership from last owner */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract TripioToken { string public name; string public symbol; uint8 public decimals; function transfer(address _to, uint256 _value) public returns (bool); function balanceOf(address who) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } contract TripioRoomNightData is Owned { using LinkedListLib for LinkedListLib.LinkedList; // Interface signature of erc165. // bytes4(keccak256("supportsInterface(bytes4)")) bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7; // Interface signature of erc721 metadata. // bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)")); bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd; // Interface signature of erc721. // bytes4(keccak256("balanceOf(address)")) ^ // bytes4(keccak256("ownerOf(uint256)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^ // bytes4(keccak256("transferFrom(address,address,uint256)")) ^ // bytes4(keccak256("approve(address,uint256)")) ^ // bytes4(keccak256("setApprovalForAll(address,bool)")) ^ // bytes4(keccak256("getApproved(uint256)")) ^ // bytes4(keccak256("isApprovedForAll(address,address)")); bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5; // Base URI of token asset string public tokenBaseURI; // Authorized contracts struct AuthorizedContract { string name; address acontract; } mapping (address=>uint256) public authorizedContractIds; mapping (uint256 => AuthorizedContract) public authorizedContracts; LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0); // Rate plan prices struct Price { uint16 inventory; // Rate plan inventory bool init; // Whether the price is initied mapping (uint256 => uint256) tokens; } // Vendor hotel RPs struct RatePlan { string name; // Name of rate plan. uint256 timestamp; // Create timestamp. bytes32 ipfs; // The address of rate plan detail on IPFS. Price basePrice; // The base price of rate plan mapping (uint256 => Price) prices; // date -> Price } // Vendors struct Vendor { string name; // Name of vendor. address vendor; // Address of vendor. uint256 timestamp; // Create timestamp. bool valid; // Whether the vendor is valid(default is true) LinkedListLib.LinkedList ratePlanList; mapping (uint256=>RatePlan) ratePlans; } mapping (address => uint256) public vendorIds; mapping (uint256 => Vendor) vendors; LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0); // Supported digital currencies mapping (uint256 => address) public tokenIndexToAddress; LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0); // RoomNight tokens struct RoomNight { uint256 vendorId; uint256 rpid; uint256 token; // The digital currency token uint256 price; // The digital currency price uint256 timestamp; // Create timestamp. uint256 date; // The checkin date bytes32 ipfs; // The address of rate plan detail on IPFS. } RoomNight[] public roomnights; // rnid -> owner mapping (uint256 => address) public roomNightIndexToOwner; // Owner Account mapping (address => LinkedListLib.LinkedList) public roomNightOwners; // Vendor Account mapping (address => LinkedListLib.LinkedList) public roomNightVendors; // The authorized address for each TRN mapping (uint256 => address) public roomNightApprovals; // The authorized operators for each address mapping (address => mapping (address => bool)) public operatorApprovals; // The applications of room night redund mapping (address => mapping (uint256 => bool)) public refundApplications; // The signature of `onERC721Received(address,uint256,bytes)` // bytes4(keccak256("onERC721Received(address,uint256,bytes)")); bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba; /** * This emits when contract authorized */ event ContractAuthorized(address _contract); /** * This emits when contract deauthorized */ event ContractDeauthorized(address _contract); /** * The contract is valid */ modifier authorizedContractValid(address _contract) { require(authorizedContractIds[_contract] > 0); _; } /** * The contract is valid */ modifier authorizedContractIdValid(uint256 _cid) { require(authorizedContractList.nodeExists(_cid)); _; } /** * Only the owner or authorized contract is valid */ modifier onlyOwnerOrAuthorizedContract { require(msg.sender == owner || authorizedContractIds[msg.sender] > 0); _; } /** * Constructor */ constructor() public { // Add one invalid RoomNight, avoid subscript 0 roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0)); } /** * @dev Returns the node list and next node as a tuple * @param self stored linked list from contract * @param _node the begin id of the node to get * @param _limit the total nodes of one page * @param _direction direction to step in */ function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction) private view returns (uint256[], uint256) { bool exists; uint256 i = 0; uint256 ei = 0; uint256 index = 0; uint256 count = _limit; if(count > self.length) { count = self.length; } (exists, i) = self.getAdjacent(_node, _direction); if(!exists || count == 0) { return (new uint256[](0), 0); }else { uint256[] memory temp = new uint256[](count); if(_node != 0) { index++; temp[0] = _node; } while (i != 0 && index < count) { temp[index] = i; (exists,i) = self.getAdjacent(i, _direction); index++; } ei = i; if(index < count) { uint256[] memory result = new uint256[](index); for(i = 0; i < index; i++) { result[i] = temp[i]; } return (result, ei); }else { return (temp, ei); } } } /** * @dev Authorize `_contract` to execute this contract&#39;s funs * @param _contract The contract address * @param _name The contract name */ function authorizeContract(address _contract, string _name) public onlyOwner returns(bool) { uint256 codeSize; assembly { codeSize := extcodesize(_contract) } require(codeSize != 0); // Not exists require(authorizedContractIds[_contract] == 0); // Add uint256 id = authorizedContractList.push(false); authorizedContractIds[_contract] = id; authorizedContracts[id] = AuthorizedContract(_name, _contract); // Event emit ContractAuthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by address * @param _contract The contract address */ function deauthorizeContract(address _contract) public onlyOwner authorizedContractValid(_contract) returns(bool) { uint256 id = authorizedContractIds[_contract]; authorizedContractList.remove(id); authorizedContractIds[_contract] = 0; delete authorizedContracts[id]; // Event emit ContractDeauthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by contract id * @param _cid The contract id */ function deauthorizeContractById(uint256 _cid) public onlyOwner authorizedContractIdValid(_cid) returns(bool) { address acontract = authorizedContracts[_cid].acontract; authorizedContractList.remove(_cid); authorizedContractIds[acontract] = 0; delete authorizedContracts[_cid]; // Event emit ContractDeauthorized(acontract); return true; } /** * @dev Get authorize contract ids by page * @param _from The begin authorize contract id * @param _limit How many authorize contract ids one page * @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0 */ function getAuthorizeContractIds(uint256 _from, uint256 _limit) external view returns(uint256[], uint256){ return getNodes(authorizedContractList, _from, _limit, true); } /** * @dev Get authorize contract by id * @param _cid Then authorize contract id * @return The authorize contract info(_name, _acontract) */ function getAuthorizeContract(uint256 _cid) external view returns(string _name, address _acontract) { AuthorizedContract memory acontract = authorizedContracts[_cid]; _name = acontract.name; _acontract = acontract.acontract; } /*************************************** GET ***************************************/ /** * @dev Get the rate plan by `_vendorId` and `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function getRatePlan(uint256 _vendorId, uint256 _rpid) public view returns (string _name, uint256 _timestamp, bytes32 _ipfs) { _name = vendors[_vendorId].ratePlans[_rpid].name; _timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp; _ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs; } /** * @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId) public view returns(uint16 _inventory, bool _init, uint256 _price) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; _price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId]; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; _price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; _init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } } /** * @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _dates The dates desc ([20180723,20180724,20180725]) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId) public view returns(uint16[] _inventories, uint256[] _prices) { uint16[] memory inventories = new uint16[](_dates.length); uint256[] memory prices = new uint256[](_dates.length); uint256 date; for(uint256 i = 0; i < _dates.length; i++) { date = _dates[i]; uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory; bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init; uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId]; if(!init) { // Get the base price inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } inventories[i] = inventory; prices[i] = price; } return (inventories, prices); } /** * @dev Get the inventory by by `_vendorId`, `_rpid` and `_date` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @return The inventory info(inventory, init) */ function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date) public view returns(uint16 _inventory, bool _init) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; } } /** * @dev Whether the rate plan is exist * @param _vendorId The vendor id * @param _rpid The rate plan id * @return If the rate plan of the vendor is exist returns true otherwise return false */ function ratePlanIsExist(uint256 _vendorId, uint256 _rpid) public view returns (bool) { return vendors[_vendorId].ratePlanList.nodeExists(_rpid); } /** * @dev Get orders of owner by page * @param _owner The owner address * @param _from The begin id of the node to get * @param _limit The total nodes of one page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightOwners[_owner], _from, _limit, _direction); } /** * @dev Get orders of vendor by page * @param _owner The vendor address * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightVendors[_owner], _from, _limit, _direction); } /** * @dev Get the token count of somebody * @param _owner The owner of token * @return The token count of `_owner` */ function balanceOf(address _owner) public view returns(uint256) { return roomNightOwners[_owner].length; } /** * @dev Get rate plan ids of `_vendorId` * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The rate plan ids and the next id */ function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction); } /** * @dev Get token ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The token ids and the next id */ function getTokens(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(tokenList, _from, _limit, _direction); } /** * @dev Get token Info * @param _tokenId The token id * @return The token info(symbol, name, decimals) */ function getToken(uint256 _tokenId) public view returns(string _symbol, string _name, uint8 _decimals, address _token) { _token = tokenIndexToAddress[_tokenId]; TripioToken tripio = TripioToken(_token); _symbol = tripio.symbol(); _name = tripio.name(); _decimals = tripio.decimals(); } /** * @dev Get vendor ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The vendor ids and the next id */ function getVendors(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendorList, _from, _limit, _direction); } /** * @dev Get the vendor infomation by vendorId * @param _vendorId The vendor id * @return The vendor infomation(name, vendor, timestamp, valid) */ function getVendor(uint256 _vendorId) public view returns(string _name, address _vendor,uint256 _timestamp, bool _valid) { _name = vendors[_vendorId].name; _vendor = vendors[_vendorId].vendor; _timestamp = vendors[_vendorId].timestamp; _valid = vendors[_vendorId].valid; } /*************************************** SET ***************************************/ /** * @dev Update base uri of token metadata * @param _tokenBaseURI The base uri */ function updateTokenBaseURI(string _tokenBaseURI) public onlyOwnerOrAuthorizedContract { tokenBaseURI = _tokenBaseURI; } /** * @dev Push order to user&#39;s order list * @param _owner The buyer address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightOwners[_owner].listExists()) { roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0); } roomNightOwners[_owner].add(_rnid, _direction); } /** * @dev Remove order from owner&#39;s order list * @param _owner The owner address * @param _rnid The room night order id */ function removeOrderOfOwner(address _owner, uint _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightOwners[_owner].nodeExists(_rnid)); roomNightOwners[_owner].remove(_rnid); } /** * @dev Push order to the vendor&#39;s order list * @param _vendor The vendor address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightVendors[_vendor].listExists()) { roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0); } roomNightVendors[_vendor].add(_rnid, _direction); } /** * @dev Remove order from vendor&#39;s order list * @param _vendor The vendor address * @param _rnid The room night order id */ function removeOrderOfVendor(address _vendor, uint256 _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightVendors[_vendor].nodeExists(_rnid)); roomNightVendors[_vendor].remove(_rnid); } /** * @dev Transfer token to somebody * @param _tokenId The token id * @param _to The target owner of the token */ function transferTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightIndexToOwner[_tokenId] = _to; roomNightApprovals[_tokenId] = address(0); } /** * @dev Approve `_to` to operate the `_tokenId` * @param _tokenId The token id * @param _to Somebody to be approved */ function approveTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightApprovals[_tokenId] = _to; } /** * @dev Approve `_operator` to operate all the Token of `_to` * @param _operator The operator to be approved * @param _to The owner of tokens to be operate * @param _approved Approved or not */ function approveOperatorTo(address _operator, address _to, bool _approved) public onlyOwnerOrAuthorizedContract { operatorApprovals[_to][_operator] = _approved; } /** * @dev Update base price of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _tokenId The digital token id * @param _price The price to be updated */ function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.init = true; vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price; } /** * @dev Update base inventory of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _inventory The inventory to be updated */ function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory; } /** * @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated */ function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The inventory to be updated */ function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); } } /** * @dev Reduce inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be reduced */ function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 a = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){ a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory; } } /** * @dev Add inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be add */ function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 c = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c; } } /** * @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated * @param _inventory The inventory to be updated */ function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Push rate plan to `_vendorId`&#39;s rate plan list * @param _vendorId The vendor id * @param _name The name of rate plan * @param _ipfs The rate plan IPFS address * @param _direction direction to step in */ function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false)); uint256 id = vendors[_vendorId].ratePlanList.push(_direction); vendors[_vendorId].ratePlans[id] = rp; return id; } /** * @dev Remove rate plan of `_vendorId` by `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function removeRatePlan(uint256 _vendorId, uint256 _rpid) public onlyOwnerOrAuthorizedContract { delete vendors[_vendorId].ratePlans[_rpid]; vendors[_vendorId].ratePlanList.remove(_rpid); } /** * @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _name The rate plan name * @param _ipfs The rate plan IPFS address */ function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs; vendors[_vendorId].ratePlans[_rpid].name = _name; } /** * @dev Push token contract to the token list * @param _direction direction to step in */ function pushToken(address _contract, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = tokenList.push(_direction); tokenIndexToAddress[id] = _contract; return id; } /** * @dev Remove token by `_tokenId` * @param _tokenId The digital token id */ function removeToken(uint256 _tokenId) public onlyOwnerOrAuthorizedContract { delete tokenIndexToAddress[_tokenId]; tokenList.remove(_tokenId); } /** * @dev Generate room night token * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _token The token id * @param _price The token price * @param _ipfs The rate plan IPFS address */ function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract returns(uint256) { roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs)); // Give the token to `_customer` uint256 rnid = uint256(roomnights.length - 1); return rnid; } /** * @dev Update refund applications * @param _buyer The room night token holder * @param _rnid The room night token id * @param _isRefund Is redund or not */ function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund) public onlyOwnerOrAuthorizedContract { refundApplications[_buyer][_rnid] = _isRefund; } /** * @dev Push vendor info to the vendor list * @param _name The name of vendor * @param _vendor The vendor address * @param _direction direction to step in */ function pushVendor(string _name, address _vendor, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = vendorList.push(_direction); vendorIds[_vendor] = id; vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0)); return id; } /** * @dev Remove vendor from vendor list * @param _vendorId The vendor id */ function removeVendor(uint256 _vendorId) public onlyOwnerOrAuthorizedContract { vendorList.remove(_vendorId); address vendor = vendors[_vendorId].vendor; vendorIds[vendor] = 0; delete vendors[_vendorId]; } /** * @dev Make vendor valid or invalid * @param _vendorId The vendor id * @param _valid The vendor is valid or not */ function updateVendorValid(uint256 _vendorId, bool _valid) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].valid = _valid; } /** * @dev Modify vendor&#39;s name * @param _vendorId The vendor id * @param _name Then vendor name */ function updateVendorName(uint256 _vendorId, string _name) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].name = _name; } }
Approve `_operator` to operate all the Token of `_to` _operator The operator to be approved _to The owner of tokens to be operate _approved Approved or not/
function approveOperatorTo(address _operator, address _to, bool _approved) public onlyOwnerOrAuthorizedContract { operatorApprovals[_to][_operator] = _approved; }
1,978,830